The reason is that a string literal (char*
)converts to bool
better than to std::string
so your string literal doesn't initialize the string
component of the variant, but rather than bool
component (to true).
See the following which outputs bool 1
:
#include <iostream>
void foo(bool b)
{
std::cout << "bool " << b << std::endl;
}
void foo(std::string s)
{
std::cout << "string " << s << std::endl;
}
int main()
{
foo("Bar");
}
Initializing with std::string("toto")
will solve your problem.
4.12/1 shows us the conversion in question:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a
prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false;
any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of
type bool; the resulting value is false.
[As noted also in the other answer] This implicit conversion takes precedence over the converting constructor of std::string
and so is selected, causing the type used in the variant to be bool
.