I have been trying to create a templated class(Test2) that takes 2 template arguments,Type1 and Type2. It is known that the second argument would also be a templated class that takes 2 template arguments(TypeA and TypeB).
Now, for constructing an object of Test2, I want the user to be able to use either of 2 types of constructors:
- One that takes objects of
Type1andType2. - One that takes objects of
Type1,TypeAandTypeB.
I wrote the following code:
#include <iostream>
template<class TypeA, class TypeB>
struct Test
{
TypeA t1obj;
TypeB t2obj;
Test(const TypeA& t1, const TypeB& t2)
: t1obj(t1), t2obj(t2) {std::cout<<"Test::Type1, Type2\n";}
};
template<class Type1,
template<typename TypeX, typename TypeY> class Type2 >
struct Test2
{
Type1 t1obj;
Type2<typename TypeX, typename TypeY> t2obj; //Line 17
Test2(const Type1& t1,
const Type2<typename TypeX, typename TypeY>& t2) //Line 20
: t1obj(t1), t2obj(t2) { std::cout<<"Test2::Type1, Type2\n";}
Test2(const Type1& t1,
const TypeX& x,
const TypeY& y)
: t1obj(t1), t2obj(x,y) { std::cout<<"Test2::Type1, X, Y\n";}
};
int main()
{
Test<int, char> obj1(1,'a');
Test2<int, Test<int, char> > strangeobj1(10,obj1);
Test2<int, Test<int, char> > strangeobj2(1,2,'b');
}
I have tried a lot but I get really absurd errors like:
wrong number of template arguments (1, should be 2) on Line 17 and 20.
It doesn’t work like that.
Test<int, char>is a full blown type, instead of a template. So you need type parametersFor getting
TypeXandTypeYit’s useful to export them so you can use them inTest2as shown above.Be sure to read Where to put the “template” and “typename” on dependent names to understand why and when to use
typenamebefore type names like above.