I need to implement a C++11 or C++14 type STRING that acts just like std:string, but has the following additional constraints/features:
- WIDTH parameter specified during declaration. STRING will throw exception if its length is greater than WIDTH
- Optional FIXED parameter specified during declaration. STRING will throw exception if its length is not equal to WIDTH
In all other respects, STRING is supposed to behave just like std::string and expose the same member functions as std:string (such as .append() etc..).
My first instinct was to use a template class STRING that holds a std::string, like so:
template<int WIDTH= 0, bool FIXED = false>
class STRING {
static_assert(WIDTH >= 0, "WIDTH of STRING cannot be negative.");
public:
STRING() : value{} { }
STRING(const std::string &s) { if (is_valid(s)) value = s; }
STRING(const char c[]) { if (is_valid(c)) value = c; }
STRING& operator=(const std::string& s){ if (is_valid(s)) value = s;}
operator std::string() const { return value; }
std::string value;
private:
bool is_valid(const std::string &s) {
if (WIDTH && s.length() > WIDTH)
throw std::length_error{"STRING assignment failed. STRING too long."};
if (FIXED && s.length() != WIDTH)
throw std::length_error{"STRING assignment failed. STRING has wrong length."};
return true;
}
};
However, the above STRING template class does not expose std::string member functions and I do not want to re-implement the entire std::basic_char function set, so I think my approach is fundamentally wrong. I suspect somehow extending std::string might be better, but it seems a little scary to "mess" with the standard library types.
I am not sure what the best approach would be here and pointers in the right direction would be more than welcome.
string1 + string2?std::string value;private). You observe the ugliness of a string class based on std::string, exposing the same (and extended) functionality.STRING<7>and aSTRING<5>creates aSTRING<12>, obviously. The "fixed" bit is slightly less obvious: the result is fixed if and only if both inputs are fixed.STRING<7>and aSTRING<7>produces anotherSTRING<7>and adding aSTRING<7>and aSTRING<5>is a compile-time error.+, then it's concatenation. Famously, Java has only case of operator overloading, and it'sString+StringPython too uses+.