Consider a C++ template class (mixin class) that inherits from the same class declared on the template, ie,
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.