本文介绍了(GCC bug?)隐式转换为派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中遇到了隐式转换的问题。以下是一个最简单的例子:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' // abstract
};
$ b $ struct ad:A {
virtual void f(){} // not abstract
};

struct B {
operator Ad()const {return Ad(); }
};

void test(A const& lhs){}

int main()
{
B b;
test(b);
}

我希望编译器执行的操作是:将b转换为键入Ad(使用B中定义的转换)并将结果传递给 test 。但是,上面的代码不能在GCC中编译(启用C ++ 11),结果是无法分配抽象类型为'A'的对象



有些事情要注意:


  1. 铿锵编译这个。

  2. 通过将 f()= 0; 更改为 f(){} 来实现非抽象,代码工作得很好。
  3. 编译器确实找到了转换运算符(如2所示),但它不会按照我希望的那样进行。


解决方案

As you can see, your conversion function isn't a candidate after this paragraph. Thus the next bullet in [dcl.init]/5 is applicable:

Note that the phrase "the program is ill-formed if the corresponding non-reference copy-initialization would be ill-formed" may imply that as

B b;
A a = b;

is ill-formed, the program is ill-formed. I believe this to be a defect or vagueness in the wording though, and not the reason that GCC does not accept the code. Assuredly the wording solely aims at the initialization itself, not the fact that a most-derived object of type T1 (aka A) can be created in the first place.
Finally 13.3.1.4 accepts our conversion function:

Now the last question is whether in

A const& ref(Ad());

ref is bound directly. And it is.
Thus the original parameter reference binds directly, and no most-derived object of type A must be created.
What GCC presumably thinks is that a temporary of type A must be initialized and the reference be bound to that temporary. Or it pedantically follows the above defected wording, which is very unlikely.


1)

这篇关于(GCC bug?)隐式转换为派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:04