boost::variant 当 bool 显示为可能的类型时,会给出错误的结果

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

本文关键字:出错 结果 错误 类型 variant bool 显示 boost      更新时间:2023-10-16

工作的代码如下:

#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)