gpt4 book ai didi

c++ - boost::variant with bool 和 string

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:54 25 4
gpt4 key购买 nike

我在使用 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::variant with bool 和 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com