c++ - 隐式类型转换看不到基类匹配。错误或功能?

标签 c++ implicit-conversion

如果转换后的类型由于基类匹配而允许函数调用,我的编译器 (GCC 4.7) 似乎不会发出隐式类型转换,即转换结果 AAB

class AB {};

class A: public AB
{
public:
  A(float i) {}
  A() {}
  A(const A& rhs) {}
  A(A&& rhs) {}
 };

AB operator*(const AB& lhs,const AB& rhs)
{
  // Return default constructed AB
}

void foo() {
  A a;
  auto tmp = 2.0 * a;   // This fails because no conversion rule was found.
}

这是C++语言的特性吗?如果是,在什么情况下不匹配基类会更好。

请不要回答说可怜的编译器有那么多事情要做,而且与基类匹配会太多。

编辑

c.cc:51:20: error: no match for ‘operator*’ in ‘2.0e+0 * a’
c.cc:51:20: note: candidate is: c.cc:42:1: note: AB operator*(const
AB&, const AB&) c.cc:42:1: note:   no known conversion for argument 1
from ‘double’ to ‘const AB&’ c.cc:51:20: error: unable to deduce
‘auto’ from ‘<expression error>’

最佳答案

Please, don't answer that the poor compiler has so much to do, and it would be too much to match against base classes.

不,但我要告诉你的是,可怜的编译器有太多事情要做,要匹配所有潜在的派生类(或通过第三种类型的其他转换)会太多

您的代码中的问题不是来自 AupcastAB ,编译器很乐意这样做,但事实上它无法转换 2.0AB .允许的转换集是有限的,并且产生有限的工作集。当您调用运算符时,它会找到一个需要两个 AB 的匹配项对象,它不知道如何直接转换 double进入AB .很明显,它可以创建一个 A temporary 然后从它向上转换,因为它向上转换了第二个参数。对于不知道从 A 派生出多少潜在类型的编译器来说,这并不明显。 (考虑单独编译的其他翻译单元)甚至可以从 double 构建的不相关类型并将转换运算符转换为 AB

关于c++ - 隐式类型转换看不到基类匹配。错误或功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232636/

相关文章:

c++ - 将数字隐式转换为整型常量

c++ - 嵌套 for 循环逻辑错误与时间逻辑错误

c++ - 如何在不收到编译器警告的情况下使用 C++ 枚举

c++11 - 使用 {} 构造函数直接从 char* 初始化 std::string

c++ - 如何防止 size_t 被解释为引用?

sql-server - EXEC 语句中的类型转换

c++ - g++参数后的逗号

c++ - 如何从图像中提取 FAST 特征?

c - 为什么 C 隐式转换像它们那样运行?

c++ - C++ 中的嵌套隐式转换