I wonder if it is possible to subclass std::string to create a new type with the same behavior, but different meaning, for example an UTF-8 string. I am thinking about something like Django's safestring
or Nim's distinct
subtypes.
I would like this type to express "this string has been created through one of my UTF-8 producing functions and is guaranteed to be valid UTF-8 (and not some other encoding)". Then the type system could prevent me from accidentially mixing encodings.
UTF-8 is just an example, it can be any other "distinct string" - e.g. "user input", "natural language" as opposed to machine readable keys, and so on. I am not trying to enforce e.g. UTF-8 validity, just origin and "flavor" (type/kind/variant) of my string. I just want to be able to write the following, and have it fail if aString
is not a MyString
:
void processString(MyString str);
// ...
processString(aString);
I have read the other discussions about subclassing std::string, but am not sure what the conclusion would be for this very specific case. My class would not have additional fields, so slicing would not be a problem, and it would not need to override methods, so it should be OK that none of std::string
's methods are virtual. Is there anything I have to define in my subclass for this to work as I want it?