I would define two types of struct in the same class, a constructor with three arguments and another with two arguments like this:
template<class A, class B, class C>
struct test{
test(A,B,C);
};
template<class A, class B>
struct test{
test(A,B);
};
In class main, when i create an instance of test with two arguments it is okay but when i create an instance of test with three arguments it throws an error: "too many arguments for model of class test".
Any suggestions please ?
CodePudding user response:
You just do:
template<class A, class B, class C>
struct test{
test(A,B,C);
test(A,B);
};
CodePudding user response:
Since you've made some effort(even though incorrect), i would try to provide an answer according to my understanding of the question which is that you want to provide 2 separate constructors for your class template one of which has 2 parameters while the other has 3 parameters. You can do so as shown below. The explanation is given as comments in the below example.
template<class A, class B, class C>
struct test{
//declaration for constructor one
test(A,B,C);
//declaration for constructor two
test(A,B);
};
//implementation for constructor one
template<class A, class B, class C>
test<A,B,C>::test(A a, B b, C c)
{
std::cout<<"constructor with 3 parameters called"<<std::endl;
}
//implementation for constructor two
template<class A, class B, class C>
test<A,B,C>::test(A a, B b)
{
std::cout<<"constructor with 2 parameters called"<<std::endl;
}
int main()
{
test<int, double, int> t1(2,2,3);//calls constructor with 3 parameters
test<int, double, int> t2(2,2);//calls constructor with 2 parameters
return 0;
}