C++语法小记---类模板

时间:2022-10-30 09:26:04
类模板
  • 类模板和函数模板类似,主要用于定义容器类

  • 类模板可以偏特化,也可以全特化,使用的优先级和函数模板相同

  • 类模板不能隐式推倒,只能显式调用

  • 工程建议:

    • 模板的声明和实现都在头文件中

    • 成员函数的实现在类外

 #include <iostream>
#include <string> using namespace std; template<typename T1, typename T2> //类模板
class Test
{
public:
void add(T1 l, T2 r)
{
cout << "void add(T1 l, T2 r)" <<endl;
}
}; template<typename T>
class Test<T, T> //偏特化
{
public:
void add(T l, T r)
{
cout << "void add(T l, T r)" <<endl;
}
}; template<>
class Test<int, int> //全特化
{
public:
void add(int l, int r)
{
cout << "void add(int l, int r)" <<endl;
}
}; int main()
{
Test<int, int> t1;
t1.add(, ); //void add(int l, int r) Test<double, double> t2;
t2.add(1.5, 2.3); //void add(T l, T r) Test<int, double> t3;
t3.add(, 2.5); //void add(T1 l, T2 r)
return ;
}
  • 在类模板中,类型可以是参数,变量也可以是参数,如复杂度为1计算阶乘
 #include <iostream>
#include <string> using namespace std; template<int N>
class Fib
{
public:
static const int value = N * Fib<N->::value;
}; template<>
class Fib<>
{
public:
static const int value = ;
}; int main()
{
cout << "Fib<5>::value = " << Fib<>::value <<endl; //Fib<5>::value = 120
return ;
}
  • 上面思路就是C++元编程的核心