I have a boost::variant with different types, where one is a (const) void pointer and another a string.
boost::variant<std::string, void const*>;
The problem is, if i want to use it with a c-string it casts it to the void pointer instead the string.
boost::variant<std::string, void const*> foo;
foo = "bar";
std::cout << foo.which(); // prints 1 -> void const*
If I remove the constness of the pointer it will cast it to the string.
boost::variant<std::string, void*> foo; // no const pointer
foo = "bar";
std::cout << foo.which(); // prints 0 -> string
Is there an easy way to make boost::variant implicitly cast the c-string to a std::string?
UPDATE
I know I can cast explicit with:
foo = std::string("bar");
But I would like to avoid the explicit casting.
You can provide your own variant template by inheriting from
boost::variant
. The correct conversion fromconst char*
tostd::string
is achieved through overloading theoperator=
:Outputs "0" as desired.
Live example: https://ideone.com/ZppUla
This idea could be even more generalized through the use of a traits class which specifies the type mapping:
Live example: https://ideone.com/AXUqTv