【发布时间】:2017-06-14 14:56:10
【问题描述】:
出于某种原因,最新版本的 GCC 和 clang 在这种特定情况下都不能识别返回类型协方差。错误信息具有误导性:
error: return type of virtual function 'foo' is not covariant with the return
type of the function it overrides ('derived *' is not derived from 'base *')
代码如下:
class base
{
private:
virtual base * foo() = 0;
};
template< class T >
class foo_default_impl : public virtual base
{
private:
T * foo() override { return nullptr; }
};
class derived : public virtual base, private foo_default_impl< derived >
{
};
int main() {
derived d{}; // error: return type of virtual function 'foo' is not covariant with the return type of the function it overrides ('derived *' is not derived from 'base *')
return 0;
}
【问题讨论】:
-
foo()需要返回foo_default_impl *,而不是T *。 -
以前的版本编译过你的代码吗?我想知道这是否是因为
derived在传递给 foo_default_impl 时还不是一个完整的类型:eel.is/c++draft/class.derived#class.virtual-8 -
@KhouriGiordano:为什么?在我们正在考虑的特定情况下,
T将是derived,而derived公开派生自base。 -
@marcinj :我认为你应该把它写下来作为答案。问题是
foo_default_impl::foo违反了规则(返回类型既不完整,也不是foo_default_impl)。错误信息可能会更好。 -
@marcin :它不完整。完整类型的其中一件事是您知道它的大小。在知道基类的大小之前,您无法知道类的大小。我们目前正在尝试创建其中一个基类!
标签: c++