【问题标题】:C++ class template as function return typeC++ 类模板作为函数返回类型
【发布时间】:2016-09-01 19:38:50
【问题描述】:

我正在做一个小项目来了解 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,在 '

提前谢谢你。

【问题讨论】:

  • 这是template(class B) 的语法正确吗?
  • 编译器应该向您显示该行。通常,如果错误提及语法,则说明您搞砸了语法。在这里,你得到了template(class B),而它应该是template&lt;class B&gt;。可能是你的伪代码,否则我会发布这个答案。
  • Base 无法看到 MyOperation,因为它是在 Base 之后定义的。
  • 对不起,我在我的项目中写对了,template&lt;class B&gt;

标签: c++ templates class-template


【解决方案1】:

声明模板的语法是template&lt;class B&gt;(或等效的template&lt;typename B&gt;)。

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

MyOperation 也引用Base(基类)。

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

template<class B> class MyOperation;

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

// 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如果定义在头文件中,则需要内联,否则如果头文件被多个源文件包含,则会出现多个链接器符号。

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

【讨论】:

  • 谢谢,我是编程新手,所以我没有考虑循环引用。
猜你喜欢
  • 2018-04-06
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 2021-03-23
  • 2015-07-20
  • 2011-03-04
  • 1970-01-01
相关资源
最近更新 更多