c++ - boost::带有 bool 和 string 的变体

标签 c++ boost

我在使用 boost::variant 时遇到问题(使用 boost 1.67.0)。

当我的模板参数列表同时包含 boolstd::string 时,任何应视为字符串的变体对象似乎都隐式绑定(bind)到 bool。例如:

using Varval = boost::variant<bool, std::string>;

void main()
{
    std::vector<Varval> vect{ true, false, "Hello_World" };

    std::cout << "[ ";
    for (const auto &v : vect)
        std::cout << v << "  ";
    std::cout << "]\n";
}

输出:

[ 1 0 1 ]

而如果我只更改第一个模板参数(从 boolint),它就可以正常工作:

using Varval = boost::variant<int, std::string>;

void main()
{
    std::vector<Varval> vect{ true, false, "Hello_World" };

    std::cout << "[ ";
    for (const auto &v : vect)
        std::cout << v << "  ";
    std::cout << "]\n";
}

正确输出:

[ 1 0 Hello_World ]

有什么想法吗?

最佳答案

boost::variant 对于每种指定类型都有一个构造函数重载。在第一个示例中,将有一个 bool 重载和一个 std::string 重载。您现在使用 char[n] 调用构造函数,该构造函数可以隐式转换为这两者。因此,没有完美的匹配,只有两个候选人。但编译器不会告诉您该调用不明确,而是选择 bool 重载作为更好的匹配。

为什么?这已经完美回答了in this question .

在使用 intstd::string 的第二个示例中,您传递的是 boolchar[n] 到构造函数。 bool 可以隐式转换为 int,但不能转换为 std::stringchar[n] 可以隐式转换为 std::string,但不能转换为 int。因此,相应的构造函数被调用,因为每个构造函数只有一个候选者。

关于c++ - boost::带有 bool 和 string 的变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957837/

相关文章:

c++ - RTTI 为多态对象存储了哪些信息?

boost - 输出 BGL 边权重

c++ - 单例析构函数

c++ - C++ 中线程所做的更改

c++ - 在 Ubuntu 上使用 OpenGL 显示闪烁

c++ - 使用 BOOST property_tree/iostreams/filesystem/foreach - 结果出现链接错误

c++ - 有效地在 Boost BGL 图中找到所有可达的顶点

c++ - 在 BOOST TEST 中添加测试套件而不是测试用例

c++ - 是否有无法获取地址的变量?

c++ - 无法使用 SDL 将角色移动到正确的位置?