繁体   English   中英

具有模板返回类型的虚拟基函数:编译器在派生类以指针类型作为模板参数的情况下失败(MSVC 2013)

[英]Virtual base function with template return type: compiler fails at derived class with pointertype as template argument (MSVC 2013)

如果我使用模板参数T = int *从CBaseInterface派生(请参见下面的代码),则编译器将出现错误C2555失败。 对于用于T的所有指针类型,都会发生这种情况。如果我改用typedef,则相同的代码可以正常工作。

// If _FALIS is defined, the compiler fails, else it succeeds
// (MS Visual Studio 2013 Update 2, 32 and 64 Bit native C++, Debug build).
#define _FALIS

#ifdef _FALIS
    #define PINT int*   
#else
    typedef int* PINT;
#endif

template <class T>
class CBaseInterface
{
public:
    virtual ~CBaseInterface() {}
    virtual const T Calculate() const = 0;
};

class CCalculator : public CBaseInterface<PINT>
{
public:
    CCalculator() {}
    virtual ~CCalculator() {}

    // error C2555: 'CCalculator::Calculate': 
    // overriding virtual function return type differs and is not 'covariant'
    // from 'CBaseInterface<int *>::Calculate'
    virtual inline const PINT Calculate() const final
    {
       return (PINT)&m_Item;
    }

protected:
    int m_Item = 0;
};

指针类型在哪里出现问题? 我很困惑,在微软的文档中找不到适合这种情况的任何东西。

希望您能够帮助我。

区别在于派生类中const PINT的含义。

如果PINTint *的typedef,则const PINTint * const (指向可变int的常量指针)-很好,这就是基类函数定义要返回的内容。 如果使用宏,则字面意义为const int * (指向常量int的可变指针),这是一种完全不同的类型。 在逻辑上将typedef替换为类型系统,将宏作为标记盲目替换。

一种解决方法是编写PINT constconst (PINT) (因此const的绑定是显式的)。

而且,您实际上不应该使用宏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM