Sau*_*nda 1 c++ templates template-templates
我一直在试图建立一个模板类(Test2即需要2个模板参数),Type1和Type2.众所周知,第二个参数也是一个带有2个模板参数(TypeA和TypeB)的模板化类.
现在,为了构造一个对象Test2,我希望用户能够使用两种类型的构造函数中的任何一种:
Type1和的对象 Type2.Type1,TypeA和TypeB.我写了以下代码:
#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');
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了很多,但我得到了非常荒谬的错误:
wrong number of template arguments (1, should be 2) 在17号线和20号线.
它不像那样工作.Test<int, char>是一个完整的类型,而不是模板.所以你需要类型参数
template<class Type1,
class Type2 >
struct Test2
{
Type1 t1obj;
Type2 t2obj; //Line 17
Test2(const Type1& t1,
const Type2& t2) //Line 20
: t1obj(t1), t2obj(t2) { std::cout<<"Test2::Type1, Type2\n";}
Test2(const Type1& t1,
const typename Type2::a_type& x,
const typename Type2::b_type& y)
: t1obj(t1), t2obj(x,y) { std::cout<<"Test2::Type1, X, Y\n";}
};
Run Code Online (Sandbox Code Playgroud)
获取TypeX并TypeY导出它们非常有用,因此您可以使用它们,Test2如上所示.
template<class TypeA, class TypeB>
struct Test
{
typedef TypeA a_type;
typedef TypeB b_type;
// and using them, to show their meaning
a_type t1obj;
b_type t2obj;
Test(const a_type& t1, const b_type& t2)
: t1obj(t1), t2obj(t2) {std::cout<<"Test::Type1, Type2\n";}
};
Run Code Online (Sandbox Code Playgroud)
请务必阅读在依赖名称上放置"模板"和"typename类型名称"的位置,以了解在上述类型名称之前使用的原因和时间.