You want to construct Numbs from a string literal. String literals are indistinguishable from type const char *
String literals have type const char [N]
, which we can take as an argument by writing a function that accepts const char *
.
To define a converting constructor with this behavior, just write a signature like that of a copy constructor, but instead of expecting an argument of the same type, expect an argument of type const char *
. Its signature would look like Myclass(const char *);
Alternatively, you can copy or move construct from strings, but that would require doing Numb n = std::string { "32" };
or similar, to convert the string constant to a std::string.
Here is some sample code, in which main() returns 3. Here we also demonstrate what to do with the value: if we instead did Num n2 = std::string { "TRAP" };
, the code would return 1. If we did Num n2 = std::string { "ANYTHING OTHER THAN TRAP" };
it would return 2.
#include <string>
struct Num {
Num()
: _val(2) {}
Num(const std::string & str) {
if (str == "TRAP") {
_val = 1;
} else {
_val = 2;
}
}
Num(const char * s) {
_val = 3;
}
int _val;
};
int main(void) {
// Num n = std::string { "TRAP" }; // returns 1
// Num n = std::string { "NOTTRAP" }; // returns 2
Num n = "TRAP";
return n._val;
}
https://godbolt.org/g/Lqwdiw
EDIT: Fix a mistake re the type system, take the string arg as & not &&, simplify example, update compiler explorer link.