我有以下代码:在返回类型的冲突从基类派生类中使用自动
struct A{};
struct Base {
virtual A& internal() = 0;
};
struct Derives : public Base {
auto& internal() override { // <-- conflicting return type
return internal_;
}
private:
A internal_;
};
int main() {
Derives d;
auto& internal = d.internal();
}
这编译失败(上coliru测试 - 用gcc)有冲突的返回类型 - 我的问题是,为什么编译器不能推断internal_
(因此返回类型)是A
?例如,在编译的不同阶段推导auto
的类型是否与检查虚拟覆盖的类型相同?当然,如果您用正确的类型替换auto
,则编译 - 但除此之外。
(这里是铛错误,海湾合作委员会是有点类似)
main.cpp:8:11: error: return type of virtual function 'internal' is not covariant with the return type of the function it overrides ('auto &' is not derived from 'A &')
auto& internal() override { // <-- conflicting return type ~~~~~^
main.cpp:4:16: note: overridden virtual function is here
virtual A& internal() = 0; ~~^
1 error generated.
想知道你为什么混合运行时多态性(虚拟函数)与优雅的编译时间类的设计(模板)? – Ajay
@BeyelerStudios,我看着这个问题,但我不相信它(虽然我可能是错的..) – Nim
在Visual Studio中,我得到:“错误C3542:导出::内部:虚拟成员函数没有包含'auto'的返回类型 –