0

Consider a C++ template class (mixin class) that inherits from the same class declared on the template, i.e.,

template <class Model>
class Mixin : public Model {
  ...
}

The motivation is to reuse this Mixin to extend methods for different Model classes. For example, for a model class ModelOne,

class ModelOne {
public: 
    ModelOne (int a, int b) { ... }
}

is 'dressed' up by the Mixin class and further extended as

class Realization : public Mixin<ModelOne> {
...
}

How do I explicitly invoke - in Realization class - the constructor of ModelOne class? Different model class may have different constructor signature.

X...
  • 173
  • 1
  • 2
  • 12

1 Answers1

1

Realization derives from Mixin<ModelOne>, so it needs to invoke the constructor for Mixin<ModelOne>, not for ModelOne directly. The constructor for Mixin can then invoke the constructor for its Model. But if Mixin doesn't know which parameters the Model constructor takes, then Mixin will have to use variadic template parameters to pass through all specified argument values, eg:

template<typename... T>
struct Mixin : T...
{
    Mixin() = delete;
    Mixin(Mixin const &) = delete;
    Mixin(Mixin &&) = delete;

    template<typename... U>
    Mixin(U&&... v) : T(std::forward<U>(v))... { }
};

class ModelOne
{
public:
    ModelOne (int a, int b) { ... }
};

class Realization : public Mixin<ModelOne>
{
...
public:
    Realization() : Mixin<ModelOne>(1, 2) {} 
}

Also see: Constructing a mixin based on variadic templates by forwarding constructor parameters

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Interesting answer. I think "variadic template parameters" fulfills the need here. – X... May 24 '20 at 05:15
  • However, the compiler kept complaining ``error: mismatched argument pack lengths while expanding ‘T’ Mixin(U &&... v) : T(std::forward (v))... {}``. This error appears in both g++-5 and g++-7 and it is perhaps not related to the compiler version. – X... May 24 '20 at 06:40
  • @Xavier my variadic template kung-fu is no so good, so I'm sure it is just a matter of tweaking the syntax to make it work. – Remy Lebeau May 24 '20 at 09:49