具有多个参数的类模板

先决条件: C++中的模板

null

创建模板时,可以指定多个类型。我们可以在一个类模板中使用多个泛型数据类型。它们在模板中声明为逗号分隔的列表,如下所示: 语法:

template<class T1, class T2, ...>
class classname
{
      ...
      ...
};

// CPP program to illustrate
// Class template with multiple parameters
#include<iostream>
using namespace std;
// Class template with two parameters
template < class T1, class T2>
class Test
{
T1 a;
T2 b;
public :
Test(T1 x, T2 y)
{
a = x;
b = y;
}
void show()
{
cout << a << " and " << b << endl;
}
};
// Main Function
int main()
{
// instantiation with float and int type
Test < float , int > test1 (1.23, 123);
// instantiation with float and char type
Test < int , char > test2 (100, 'W' );
test1.show();
test2.show();
return 0;
}


输出:

1.23 and 123
100 and  W

代码说明:

  • 在上面的程序中,测试构造函数有两个泛型类型的参数。
  • 参数类型在尖括号中提到 < > 在创建对象时。
  • 当参数不止一个时,它们用逗号分隔。
  • 以下声明
    Test  test1 (1.23, 123);

    告诉编译器第一个参数的类型为 浮动 另一个是 智力 类型

  • 在创建对象的过程中,调用构造函数并通过模板参数接收值。

本文由 萨希·提瓦里 .如果你喜欢极客(我们知道你喜欢!)如果你想投稿,你也可以用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享