升压变暧昧建设 [英] Boost variant ambiguous construction

查看:127
本文介绍了升压变暧昧建设的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

升压变的文件接受任意类型的构造以下称

 模板< typename的T>变种(T&安培;操作数);


  • 要求: T必须明确地转换为有界类型之一(即T1,T2等)

同样是构造函数接受真正的常量T&安培; T&放大器;&安培; 。因此,我希望下面的code将不能编译:

 的boost ::变体LT;的std ::字符串,布尔> V =文本;

不过,code编译和 v 成为一个布尔值,这是我绝对不想。当然,解决办法是换行字符串在的std ::字符串构造函数。我的问题是:


  1. 为什么这个code编译?

  2. 它是如何选择的类型(如为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:

  1. Why does this code compile?
  2. How does it choose the type (as const char* is convertible to both std::string and bool)?

解决方案

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:

这篇关于升压变暧昧建设的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆