Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 239
Mathias Vorreiter Pedersen Avatar asked Mar 26 '13 11:03

Mathias Vorreiter Pedersen


1 Answers

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.

like image 195
Angew is no longer proud of SO Avatar answered Sep 29 '22 22:09

Angew is no longer proud of SO