How to write a template, that would take as argument classes, whose constructors have mutually exclusive signatures?
class A
{
A(){};
public:
int a;
A(int i) : a(i) {};
};
class B{
B(){};
public:
int a,b;
B(int i,int j) : a(i), b(j) {};
};
template <class T> class C {
public:
T* _t;
C(int i[])
{ //???
_t=new T(i[0]); //if T has T(int) signature
_t=new T(i[0],i[1]); //if T has T(int,int) signature
}
~C() {delete _t;}
};
int main()
{
int Ai[]={1,2};
C<A> _c(Ai); // template should work instantiated with A and B
C<B> _c(Ai); //
return 0;
}
The signatures of A and B are fixed (cannot be changed to int[] e.g.). Context: I’m thinking about a wrapper, that would take a (specialized) container type as the template argument, e.g. T=vector<int>, or T=map<int,int>, and the problem arises when constructors need to be called.
Use a variadically-templated constructor:
Usage:
(Real programmers would of course prefer a member
std::unique_ptr<T> _t;, with otherwise unchanged semantics, but allowing you to disregard all the comments.)