samedi 27 octobre 2018

How to instantiate a templated class with non-default constructors

Please consider the following example:

class Generator {
public:
    Generator(int n)
        : m_n(n)
    {
    }

    int f()
    {
        return m_n;
    }
private: 
    int m_n;
};

template<class BaseClass>
class Transformer : public BaseClass
{
public:
    Transformer(int mult, int add)
        : m_mult(mult)
        , m_add(add)
    {

    }

    int f()
    {
        return BaseClass::f() * m_mult + m_add;
    }

private:
    int m_add;
    int m_mult;
};

Imaging there are more Generator classes, which have different arguments in their constructors. Now I want to instantiate a class consisting of both passing all the required parameters. So I tried the following, but Generator is apparently not recognized as a base class:

class TG : public Transformer<Generator>
{
public:
    TG(int n, int mult, int add)
        : Generator(n)              // error C2614: 'TG': illegal member initialization: 'Generator' is not a base or member
        , Transformer(mult, add)
    {}
};

TG t(n,mult,add);

Next I tried template specialization:

template<> Transformer<Generator>::Transformer(int n, int mult, int add)    // error C2244: 'Transformer<Generator>::Transformer': unable to match function definition to an existing declaration
    : Transformer(mult,add)
    , Generator(n)
{};

Transformer<Generator> t(n,mult,add);

How can I instantiate a template, which has non-default constructors?

Aucun commentaire:

Enregistrer un commentaire