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

标签 c++ boost boost-variant

有效的代码如下:

#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 的行

将 map 定义的行修改为:

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

输出不同:

a = 10
b = c = 

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

最佳答案

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

修复方法是 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)

关于c++ - 当 bool 作为可能的类型出现时,boost::variant 会给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072688/

相关文章:

ubuntu - 用 1.50 替换默认的旧 boost 1.46

python - 在 boost::odeint 中指定插值时间

c++ - boost::variant 的问题,链接器给出段错误

c++ - 使用 lambda 进行变体访问的最佳方法

c++ - 使用额外参数 boost 变体访问者

c++ - Clang 中带有静态 constexpr 的奇怪的循环模板模式 (CRTP)

c++ - 管道类存储具有约束的不同模板

c++ - 点的坐标迭代器

C++/C : Trim the first word of each line of a text file

C++ 文件 IO : read input of "29.0" to double but output is "29", 即 ".0"已删除