c++boostboost-variantapply-visitor

boost::variant visitor chooses the wrong overload


Why does the following print out "A boolean!"? I realise there are some weird conversion going on, since if I explicitly construct a std::string I get the correct behavior. But why does overload resolution choose visitor::operator()(bool) in the following case?

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

typedef boost::variant<bool, std::string> type;

struct visitor : public boost::static_visitor<> {
    void operator()(bool b) const {
        std::cout << "A boolean!" << std::endl;
    }

    void operator()(const std::string& str) const {
        std::cout << "A string!" << std::endl;
    }
};

int main(int argc, char* argv[]) {
    type t = "I am a string";
    t.apply_visitor(visitor());

    return 0;
}

I am running Visual Studio 2012 (CTP or not gives the same result)


Solution

  • You're initialisng t with a (type that decays to) const char*. Converting a pointer to bool is a standard conversion, while converting const char* to std::string is a user-defined conversion. The standard conversion takes precedence.