c++类模板作为函数返回类型
C++ class template as function return type
我正在做一个小项目,以了解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
如果定义在头文件中,则需要内联,否则如果头文件包含在多个源文件中,则会有多个链接符。
如果它不是内联的(如果它是一个大函数更好),那么定义应该放在源文件中。
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 在 c++ 中将函数返回类型指定为模板参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何避免模板函数返回类型重复?
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在某些情况下从函数返回类型中删除 cv 限定符?
- 模板类内模板类的函数返回类型
- 为什么函数返回类型中不允许参数推导?
- 函数返回类型之前的"define"
- C++推断要隐式调用的模板函数返回类型
- 具有不同模板参数的函数返回类型
- 当函数返回类型为父类时,如何返回子类的对象?
- C++:在原型中声明"auto"函数返回类型仍然会导致在扣除错误之前使用"auto&quo
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 函数返回类型中的模板类型推断
- 嵌套模板类返回类型在 C++ 中的头文件中函数返回类型的语法
- C++重写 void 函数返回类型会导致生成失败
- 从函数内部推断函数返回类型
- C++嵌套类函数返回类型和命名空间