I was working with boost::variant
and its visitors when I runned into an unexpected behavior: the string and bool values were comparable
OK, now that you've completely changed your program, let me try again.
The problem is:
datatype *b = new datatype("abc");
"abc"
is a const char*
, not a std::string
. If you want to create a std::string
variant, you need to do so explicitly. Otherwise, you'll end up creating a bool
variant because all pointers are convertible to bool
, including const char*
pointers.
Try this
datatype *b = new datatype(std::string("abc"));
This interaction between bool
and std::string
is apparently well-known and somewhat irritating. boost::variant
provides a templated constructor, but the resolution rules prefer the built-in converstion to bool
and there's no way in C++ to specify a template specialization on a constructor. It is possible to explicitly specialize assignment, so you can write:
datatype b;
b.operator=<std::string>("abc");
which might be marginally more efficient but much less readable than
datatype b;
b = std::string("abc");
If you don't include bool
as a variant, then string literals do automatically convert to std::string
. Maybe it's possible to use some sort of proxy pseudo-boolean class. I've never tried.