布尔值和字符串的boost :: variant [英] boost::variant with bool and string
问题描述
我在 boost :: variant
上遇到了麻烦(使用Boost 1.67.0).
I'm having trouble with boost::variant
(using boost 1.67.0).
当我的模板参数列表同时包含 bool
和 std :: string
时,应视为字符串的任何变体对象似乎都隐式绑定到bool上.例如:
When my template parameter list includes both bool
and std::string
, any variant objects which should be treated as string, seem to be implicitly bound to bool instead. For example:
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]
[ 1 0 1 ]
如果我只更改第一个模板参数,从 bool
更改为 int
,它就可以正常工作:
whereas if I change nothing but the first template argument, from bool
to int
, it works fine:
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]
[ 1 0 Hello_World ]
有什么想法吗?
推荐答案
boost :: variant
对于每种声明的类型都有一个构造函数重载.在您的第一个示例中, bool
将有一个重载,而 std :: string
则有一个重载.现在,您可以使用 char [n]
调用构造函数,该函数可以隐式转换为它们两者.因此,没有完美的匹配,只有两个候选人.但是,编译器将选择 bool
重载作为更好的匹配,而不是告诉您该调用是模棱两可的.
boost::variant
has one constructor overload for each stated type. In your first example there will be one overload for bool
and one for std::string
. You are now calling the constructor with a char[n]
which can be imlicitly converted to both of them. So there is no perfect match but two candidates. But instead of telling you that the call is ambiguous, the compiler will choose the bool
overload as the better match.
为什么?在这个问题中,这已经得到了完美的答案.
Why? That is already perfectly answered in this question.
在使用 int
和 std :: string
的第二个示例中,您要传递 bool
s和 char [n] 代码>到构造函数.
bool
可以隐式转换为 int
,但不能转换为 std :: string
. char [n]
可以隐式转换为 std :: string
,但不能转换为 int
.因此,将相应的构造函数称为构造函数",因为每个构造函数只有一个候选.
In your second example with int
and std::string
you are passing bool
s and char[n]
to the constructors. bool
is implicitly convertable to int
but not to std::string
. char[n]
is implicitly convertable to std::string
but not to int
. So the according constructors are called as there is only one candidate for each.
这篇关于布尔值和字符串的boost :: variant的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!