C++ 错误 : conflicting return type specified for. .. 模板化子类

标签 c++ templates

乍一看,一切似乎都是正确的,但这段代码无法编译。但是,如果我将基类的返回类型更改为 double * 那么它将编译。有人可以解释编译器如何/为什么不将模板类型“T”视为有效的返回类型。

基类:

01 template <typename T>
02 class DefaultValueFunctorBase {
03   public:
04     virtual const T operator() (void) const = 0;
05 };

子类:

01 class DblPtrDft : public DefaultValueFunctorBase<double *> {
02   public:
03     DblPtrDft (double default_value_)
04     : DefaultValueFunctorBase<double *>(),
05       _default_value(default_value_),
06       _default_value_ptr(&_default_value)
07     {}
08 
09     const double * operator() (void) const { return _default_value_ptr; }
10 
11   private:
12     const double *_default_value_ptr;
13     const double _default_value;
14 };

错误:

DblPtrDft.h:09: error: conflicting return type specified for ‘virtual const double* DblPtrDft::operator()() const’ DefaultValueFunctorBase.h:04: error: overriding ‘const T DefaultValueFunctorBase::operator()() const [with T = double*]’

最佳答案

问题是 const T 应该读作 T const,这清楚地表明 const 限定符适用于 T。因此,当您在模板实例化中将 T 替换为 double* 时,您得到的基类调用运算符的返回类型是 double* const

这与您在派生类的调用运算符中的返回类型不同(即 const double*,等同于 double const*)。在父类(super class)中,您返回一个指向 double 的常量指针。在子类上,您返回一个指向常量 double 的非常量指针。

修复应用程序的一种方法是:

template<typename T>
class DefaultValueFunctorBase
{
    public:
        // Do not return T const here: the top-level const is useless anyway
        virtual T operator() (void) const = 0;
};

// Instantiate your base class template with double const* rather than double*
class DblPtrDft : public DefaultValueFunctorBase<double const*>
{
public:
    DblPtrDft (double default_value_)
    : DefaultValueFunctorBase<double const*>(), // Same change here of course...
    _default_value(default_value_),
    _default_value_ptr(&_default_value)
    {}

    // Return a double const*, consistently with the instantiated template...
    double const* operator() (void) const { return _default_value_ptr; }

private:
    double const*_default_value_ptr;
    double const _default_value;
};

关于C++ 错误 : conflicting return type specified for. .. 模板化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14948303/

相关文章:

c++ - 带模数的随机数生成器

c++ - 显式实例化

c++ - 函数模板 : extern template vs explicit specialisation

c++ - 模板函数给出 "no matching function for call"错误

c++ - 获取相对于特定目录的文件路径

C++,Ifstream 打开本地文件但不打开 HTTP 服务器上的文件

c++ - Linux C++ 线程已死,但 "hanging"- 线程限制

c++ - 将float转换为int,当int溢出范围时,将其设为max int或min int

C++模板特化方法问题

c++ - 如何在模板结构中使用包装的 typedef 修复 C++ 编译