由於某些原因,GCC和clang的最新版本無法識別此特定場景中的返回類型協方差。該錯誤消息是誤導:Covariant返回類型不被識別
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時還不是一個完整的類型:http://eel.is/c++draft/class.derived#class.virtual-8 – marcinj
@KhouriGiordano:爲什麼?在我們正在考慮的特定情況下,'T'將會是'derived',並且'derived'是從'base'公開派生的。 –