c++ - boost::get boost::variant no giving the correct output -


i have following function

template <typename t, typename u> const t* visitor_fct(u& operand) {   return (boost::get<t>(&operand)); } 

when do

 boost::variant<int, std::string> str = "string";  std::cout << visitor_fct<std::string>(str) << std::endl; 

i correct output

but when change declaration of str :

boost::variant<int, std::string, bool> str = "toto";

i getting nullptr;

why ?

the reason string literal (char*)converts bool better std::string string literal doesn't initialize string component of variant, rather bool component (to true).

see following 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 std::string("toto") solve problem.

4.12/1 shows conversion in question:

a prvalue of arithmetic, unscoped enumeration, pointer, or pointer member type can converted prvalue of type bool. 0 value, null pointer value, or null member pointer value converted false; other value converted true. prvalue of type std::nullptr_t can converted prvalue of type bool; resulting value false. 

[as noted in other answer] implicit conversion takes precedence on converting constructor of std::string , selected, causing type used in variant bool.


Comments