vendredi 24 juillet 2015

Fix circular dependency in arithmetic class

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?

Aucun commentaire:

Enregistrer un commentaire