这个用户定义的转换是否含糊不清?如果是,什么规则允许呢? [英] Is this user-defined conversion not ambiguous? If so, what rule allows it?

查看:63
本文介绍了这个用户定义的转换是否含糊不清?如果是,什么规则允许呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


[C ++ 11:12.3 / 2]:用户定义的转换仅在它们是明确的时候应用。 [..]

[C++11: 12.3/2]: User-defined conversions are applied only where they are unambiguous. [..]

但是,以下在GCC中编译正常和ang中继:

Yet, the following compiles just fine in GCC and Clang trunk:

struct B;
struct A
{
    A();
    operator B();
};

struct B
{
    B(const A&);
};

int main()
{
    A a;
    (B)a;
}

我缺少什么?

推荐答案

在这种情况下,转换符号(B)a 等效于 static_cast< B& (a)(§5.4/ 4)。这又具有与初始化 B t(a)相同的语义,其中 t 是临时的.9 / 4)。由于 B 有类类型,并且初始化是直接初始化,因此只考虑 B 的构造函数8.5 / 16)。适用的构造函数是:

The cast notation (B)a is equivalent in this case to static_cast<B>(a) (§5.4/4). This in turn has the same semantics as the initialization B t(a), where t is a temporary (§5.2.9/4). Since B has class type, and the initialization is a direct-initialization, only the constructors of B are considered (§8.5/16). The applicable constructors are:


  • 转换构造函数 B :: B(const A&)

  • 隐式定义的复制构造函数 B :: B(const B&)

  • 定义的移动构造函数 B :: B(B&&)

  • converting constructor B::B(const A&)
  • implicitly defined copy constructor B::B(const B&)
  • implicitly defined move constructor B::B(B&&)

因为从 A const A& 的隐式转换是完全匹配。

The converting constructor wins overload resolution since the implicit conversion from A to const A& is an exact match.

这篇关于这个用户定义的转换是否含糊不清?如果是,什么规则允许呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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