升压变暧昧建设 [英] Boost variant ambiguous construction
问题描述
升压变的文件接受任意类型的构造以下称
模板< typename的T>变种(T&安培;操作数);
- 要求: T必须明确地转换为有界类型之一(即T1,T2等)
同样是构造函数接受真正的常量T&安培;
和 T&放大器;&安培;
。因此,我希望下面的code将不能编译:
的boost ::变体LT;的std ::字符串,布尔> V =文本;
不过,code编译和 v
成为一个布尔值,这是我绝对不想。当然,解决办法是换行字符串在的std ::字符串
构造函数。我的问题是:
- 为什么这个code编译?
- 它是如何选择的类型(如
为const char *
可转换为两个的std ::字符串
和布尔
)?
一般情况下,用户定义的转换失去重载解析过程中的标准转换。
有从为const char
指针布尔
内置的转换是preferred在无内置转换从为const char *
到的std ::字符串
(如见的隐式转换的)
的std ::字符串
,而标准库的一部分,不是一个内置的类型,因此它的转换构造函数只考虑了转换后的内置类型。
一些参考文献:
The Boost Variant documentation says the following of the constructor that accepts arbitrary type:
template<typename T> variant(T & operand);
- Requires: T must be unambiguously convertible to one of the bounded types (i.e., T1, T2, etc.).
The same is true of the constructors accepting const T&
and T&&
. So I expect that the following code won't compile:
boost::variant<std::string, bool> v = "text";
But the code compile, and v
becomes a bool, which is something I definitely did not want. Of course the solution is to wrap the string literal in a std::string
constructor. My question is:
- Why does this code compile?
- How does it choose the type (as
const char*
is convertible to bothstd::string
andbool
)?
Generally, user-defined conversions lose overload resolution process to standard conversions.
There is a built-in conversion from const char
pointers to bool
which is preferred over the non-built-in conversion from const char *
to std::string
(e.g. see Implicit conversions).
std::string
, while part of the standard library, is not a built-in type so its conversion constructors are considered only after conversions to built-in types.
Some references:
- Why does the compiler choose bool over string for implicit typecast of L""?
- Why is my overloaded C++ constructor not called?
这篇关于升压变暧昧建设的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!