0

The code that works is the following:

#include <boost/variant.hpp>
#include <string>
#include <map>
#include <iostream>

int main(int argc, char** argv) {

    std::map<std::string, boost::variant<int, std::string> > values;
    values["a"] = 10;
    values["b"] = "bstring";
    values["c"] = "cstring";


    for (const auto &p : values) {
            std::cout <<  p.first <<  " = ";

        if (p.second.type() == typeid(std::string)) {
            std::cout <<  boost::get<std::string>( p.second ) << " (found string)" << std::endl;
        } else if ( p.second.type() == typeid(int)) {
            std::cout << boost::get<int>( p.second ) << " (found int)" << std::endl;
        } else if ( p.second.type() == typeid(bool)) {
            std::cout << boost::get<bool>( p.second ) << " (found bool)" << std::endl;
        } else {
            std::cout << " not supported type " << std::endl;
        }
    }

}

The output (g++ test.cpp -std=c++11):

a = 10 
b = bstring 
c = cstring

The code that does not work is exactly the same, except the line that defines the std::map

modifying the line of the map definition to:

std::map<std::string, boost::variant<int, std::string, bool> > values;

the output is different:

a = 10
b = c = 

The if statement that refers to std::string comparison does not succeed. What is the problem?

cateof
  • 6,608
  • 25
  • 79
  • 153

1 Answers1

2

In your code, values["b"] = "bstring"; creates a bool value, when both std::string and bool are in the variant type.

A fix is values["b"] = std::string("bstring");.

Or, in C++14:

using namespace std::string_literals;
values["b"] = "bstring"s;

It is a well-known annoyance that string literals better convert to bool than to std::string:

#include <iostream>
#include <string>

void f(std::string) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
void f(std::string const&) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
void f(bool) { std::cout << __PRETTY_FUNCTION__ << '\n'; }

int main() {
    f("hello");
}

Outputs:

void f(bool)
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 1
    It would be helpful to mention [`operator""s`](http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s). – You May 19 '17 at 15:00