I have some templated classes like the ones below
template<typename T>
class A{
public:
A(T a0, T a1, T a2):a0_(a0),a1_(a1),a2_(a2){}
private:
T a0_,a1_,a2_;
};
template<typename T>
class B{
public:
B(T a, std::vector<T> b):a_(a),b_(b){}
private:
T a_;
std::vector<T> b_;
};
template<typename T>
class C{
public:
C(T a, T b, std::vector<T> c):a_(a),b_(b),c_(c){}
private:
T a_,b_;
std::vector<T> c_;
};
In general the classes constructor have an arbitrary number of arguments and optionally a std::vector
in the end.
I wish to make a getter function that will allocate an instance of the above classes.
template< typename C, typename... Args>
C* get(Args... args){
return new C(args...);
}
The getter function compiles successfully when the vector is explicitly created/defined.
A<int>* aa = get< A<int> >(1,2,3);
std::vector<int> v({1,2,3});
B<int>* bb = get< B<int> >(1,v);
C<int>* cc = get< C<int> >(1,2,v);
B<int>* bb = get< B<int> >(1,std::vector<int>({1,2,3}));
C<int>* cc = get< C<int> >(1,std::vector<int>({1,2,3}));
For usage simplicity, I would like to use initializer list to define the vector in B
and C
. This works fine when calling constructor directly.
A<int>* aa = new A<int>(1,2,3);
B<int>* bb = new B<int>(1,{1,2,3});
C<int>* cc = new C<int>(1,2,{1,2,3});
The getter function however gives a compile error
B<int>* bb = get< B<int> >(1,{1,2,3});
C<int>* cc = get< C<int> >(1,2,{1,2,3});
error: too many arguments to function ‘C* get(Args ...) [with C = B; Args = {}]’
Creating a function specialization handling the vector like below was unsuccessful, too.
template< typename C, typename T, typename... Args>
C* get(Args... args, std::vector<T> v){
return new C(args...,v);
}
Is it possible to create a getter function that will get the argument pack and the initializer list as last argument and create the object?
I use gcc 5.4 to compile.