c++类模板作为函数返回类型

C++ class template as function return type

本文关键字:函数 返回类型 c++      更新时间:2023-10-16

我正在做一个小项目,以了解c++模板是如何工作的。基本上,我有这样的东西:

class Base{
public:
    MyOperation<Base> operate(Base x){ return MyOperation<Base>(x); } //error here
};
//...
template<class B>
class MyOperation : public Base{
public:
    B b;
    MyOperation(B b_){ b = b_; }
};

当我尝试编译我的程序时,我得到一个错误(错误C2143,在'<'之前缺少';')。是因为我不能把MyOperation作为函数operate()的返回类型吗?

提前感谢。

声明模板的语法是template<class B>(或等价的template<typename B>)。

也有一个循环引用:Base引用MyOperation(返回类型和operate函数内部)。所以MyOperation需要在Base之前定义。

但是MyOperation也引用了Base(基类)。

对于基类和函数内部的使用,需要一个完整的定义。但是对于返回类型,一个不完整类型就足够了。因此,MyOperation需要在Base之前预先声明,如:

template<class B> class MyOperation;

此外,operate()需要在MyOperation定义之后,在class Base { ... }之外定义(而不是声明)。正确的代码应该是:

// pre-declaration of MyOperation
template<class B> class MyOperation;
// definition of Base class
class Base {
public:
    // declaration of Base::operate member function
    // MyOperation<Base> is incomplete type here
    MyOperation<Base> operate(Base x);
};   
// definition of MyOperation class template
template<class B>
class MyOperation : public Base{
public:
    B b;
    MyOperation(B b_){ b = b_; }
};
// definition ofBase::operate member function
inline MyOperation<Base> Base::operate(Base x) {
    return MyOperation<Base>(x);
}

Base::operate如果定义在头文件中,则需要内联,否则如果头文件包含在多个源文件中,则会有多个链接符。

如果它不是内联的(如果它是一个大函数更好),那么定义应该放在源文件中。