Replace your existing constructor with this constructor:
MyClass(const T1& t1 = T1(), const T2& t2 = T2()):first(t1), second(t2) {}
Вопрос
My code is
template <class T1, class T2>
class MyClass
{
T1 first;
T2 second;
public:
//default constructor
MyClass():first(T1()), second(T2()) {}
}
I want to have a single constructor which can take 0, 1 or 2 arguments (parameters as default). Here T1 and T2 can be both primitive as well as non-primitive types.
Решение
Replace your existing constructor with this constructor:
MyClass(const T1& t1 = T1(), const T2& t2 = T2()):first(t1), second(t2) {}
Другие советы
Try this:
template <class T1, class T2>
class MyClass
{
T1 first;
T2 second;
public:
//default constructor
MyClass(T1 fst=T1(), T2 sec = T2()):first(fst), second(sec) {}
};
int main()
{
MyClass<int,int> c;
MyClass<int,int> d(5);
MyClass<int,int> e(5,10);
}
You have to just assign the default value in the definition. You have to be careful that default arguments are always the last in the list of arguments. And that one constructor is all that's needed in all the situations of 0, 1 or 2 arguments.
Default parameters can be use in constructor initializer list as for all other functions.
MyClass(T1 t1 = T1(), T2 t2 = T2()) : first(t1), second(t2) {}