本文介绍了修正算术类中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组类实现奇怪的循环模板模式。然而,诀窍是基类需要返回子类的实例。这里有一个例子:
template< typename SubType>
class ArithmeticBase
{
public:
template< typename OtherType>
const加法运算符+(const OtherType& other)
{return Addition(get_subclass(),other);}
// ...
//用于减法,乘法,除法,...
private:
const SubType& get_subclass()const
{return * static_cast< const SubType *> }
};
template< typename OperatorType1,typename OperatorType2>
类加法:ArithmeticBase<加法< OperatorType1,OperatorType2>>
{
public:
添加(const OperatorType1& op1,const OperatorType2& op2)
:op1(op1)
,op2(op2)
{}
private:
const OperatorType1& op1;
const OperatorType2& op2;
};
// ...
//减法,乘法,除法等其他类
编译失败,因为添加
类未在 ArithmeticBase
class:
arithmetic.cpp:6:8:error:unknown type name'Addition'
const加法如何解决这个问题? p>
解决方案您可以在基类之前转发添加
。
模板< typename OperatorType1,typename OperatorType2>
类加法;
template< typename SubType>
class ArithmeticBase
{
...
};
这允许编译器知道有一个类型添加
在定义之前存在。
I have a set of classes implementing the curiously recurring template pattern. However, the trick is that the base class needs to return instances of the subclasses. Here's an example:
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, ...
Compiling this fails because the Addition
class is not defined before it's used in the ArithmeticBase
class:
arithmetic.cpp:6:8: error: unknown type name 'Addition'
const Addition operator+(const OtherType &other)
^
How can I resolve this?
解决方案 You could forward declare Addition
before the base class.
template <typename OperatorType1, typename OperatorType2>
class Addition;
template <typename SubType>
class ArithmeticBase
{
...
};
This allows the compiler to know there is a type Addition
that exists before it is defined.
这篇关于修正算术类中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!