I'm trying to inherit from a bunch of classes of which I know an interface, but however they may have very different constructors. To do so I decided to use variadic templates into the derived class constructor, so that it may get the arbitrary parameters that will in the end feed the parent class.
My code is the following:
#include <iostream>
struct A {
A(int) { std::cout << "This is int\n"; }
A(unsigned) { std::cout << "This is unsigned\n"; }
};
struct B {
B(char) { std::cout << "This is char\n"; }
};
template <typename T>
struct C : public T {
template <typename... Args>
C(double, Args&&... params) : T(std::forward<Args>(params)...) { std::cout << "This is double\n"; }
// But what about this?
// C(Args&&... params, double) : T(std::forward<Args>(params)...) { std::cout << "This is double\n"; }
};
int main() {
C<A> p(1.0, 1);
C<A> r(1.0, 1u);
C<B> q(1.0, 'c');
// Which would work as following
// C<A> p(1, 1.0);
// C<A> r(1u, 1.0);
// C<B> q('c', 1.0);
return 0;
}
My questions are:
- Is this code correct? This is my first attempt with variadic templates in constructors, so I'd love to hear your opinion if I missed something.
- I'd prefer to leave the parameters of the child class
C
at the end, however as far as I understand this is not possible since in a constructor you are not allowed to specify the template parameters, and in that case the variadic arguments would swallow all the parameters, leaving none for the actual child. Is there a way to do this by any chance?