讲解C++的模板推到流程
#include <iostream>
#include <string>
using namespace std;
class Test_1
{
public:
static const int TS = 1;
};
class Test_2
{
public:
struct TS
{
int value;
};
};
template
< class T >
void test_class()
{
typename T::TS *a; // 1. 通过泛指类型 T 内部的数据类型 TS 定义指针变量 a (推荐的解读方式)
// 2. 使用泛指类型 T 内部的静态成员变量 TS 与全局变量 a 进行乘法操作
}
int main(int argc, char *argv[])
{
//test_class<Test_1>();
test_class<Test_2>();
return 0;
}
函数推到,在函数声明中要求函数模板自动推到类型时,必须能够严格匹配,显示类型指定时,能够进行隐式类型的转换。
#include <iostream>
#include <string>
using namespace std;
class Test
{
Test(const Test&);
public:
Test()
{
}
};
template < typename T >
void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
typedef void(FuncI)(int&, int&);
typedef void(FuncD)(double&, double&);
typedef void(FuncT)(Test&, Test&);
int main()
{
FuncI* pi = Swap; // 编译器自动推导 T 为 int
FuncD* pd = Swap; // 编译器自动推导 T 为 double
FuncT* pt = Swap; // 编译器自动推导 T 为 Test
cout << "pi = " << reinterpret_cast<void*>(pi) << endl;
cout << "pd = " << reinterpret_cast<void*>(pd) << endl;
cout << "pt = " << reinterpret_cast<void*>(pt) << endl;
return 0;
}