boost::variant 当 bool 作为可能的类型出现时给出错误的结果

boost::variant gives wrong result when bool appears as possible type

有效的代码如下:

#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;
        }
    }

}

输出(g++ test.cpp -std=c++11):

a = 10 
b = bstring 
c = cstring

不起作用的代码完全相同,除了定义 std::map

的行

将地图定义的行修改为:

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

输出不同:

a = 10
b = c = 

引用std::string比较的if语句不成功。有什么问题?

在您的代码中,当 std::stringbool 都属于变体类型时,values["b"] = "bstring"; 会创建一个 bool 值。

修复是 values["b"] = std::string("bstring");

或者,在C++14中:

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

众所周知,字符串文字转换为 bool 比转换为 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");
}

输出:

void f(bool)