std ::变体和模棱两可的初始化
考虑以下代码:
void fnc(int)
{
std::cout << "int";
}
void fnc(long double)
{
std::cout << "long double";
}
int main()
{
fnc(42.3); // error
}
由于对 fnc
的调用不明确,它给出了错误。
但是,如果我们编写下一个代码:
std::variant<int, long double> v{42.3};
std::cout << v.index();
输出为 1
,这表明已选择 double
->long double
转换。 据我所知,std::variant
遵循有关转换等级的 C++ 规则,但这个示例显示了差异。对于这种行为有什么解释吗?
Consider the following code:
void fnc(int)
{
std::cout << "int";
}
void fnc(long double)
{
std::cout << "long double";
}
int main()
{
fnc(42.3); // error
}
It gives an error because of an ambiguous call to fnc
.
However, if we write the next code:
std::variant<int, long double> v{42.3};
std::cout << v.index();
the output is 1
, which demonstrates that the double
->long double
conversion has been chosen.
As far as I know, std::variant
follows the C++ rules about conversion ranks, but this example shows the difference. Is there any explanation for such a behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 P0608 之前,
变体v{42.3}
自42.3
以来也存在不明确的问题可以转换为int
或long double
。P0608 更改了
variant
构造函数的行为:在您的示例中,
variant
有两种替代类型:int
和long double
,因此我们可以构建以下表达式Since 只有
#2
格式良好,变体
成功推导出所包含值类型的类型长双精度
。Before P0608,
variant<int, long double> v{42.3}
also has the ambiguous issue since42.3
can be converted toint
orlong double
.P0608 changed the behavior of
variant
's constructors:In your example, the
variant
has two alternative types:int
andlong double
, so we can build the following expressionSince only
#2
is well-formed, thevariant
successfully deduces the type of the contained value typelong double
.