【发布时间】:2015-07-24 15:23:06
【问题描述】:
我有一组实现奇怪重复的模板模式的类。然而,诀窍是基类需要返回子类的实例。这是一个例子:
template <typename SubType>
class ArithmeticBase
{
public:
template <typename OtherType>
const Addition operator+(const OtherType &other)
{return Addition(get_subclass(), other);}
// ...
// Operators for subtraction, multiplication, division, ...
private:
const SubType &get_subclass() const
{return *static_cast<const SubType*>(this);}
};
template <typename OperatorType1, typename OperatorType2>
class Addition : ArithmeticBase<Addition<OperatorType1, OperatorType2>>
{
public:
Addition(const OperatorType1 &op1, const OperatorType2 &op2)
: op1(op1)
, op2(op2)
{}
private:
const OperatorType1 &op1;
const OperatorType2 &op2;
};
// ...
// Additional classes for subtraction, multiplication, division, ...
编译失败是因为Addition 类在用于ArithmeticBase 类之前没有定义:
arithmetic.cpp:6:8: error: unknown type name 'Addition'
const Addition operator+(const OtherType &other)
^
我该如何解决这个问题?
【问题讨论】:
-
非会员好友运营商?
标签: c++ templates c++11 circular-dependency crtp