C++

调用成员模板

Posted by DEVIN on Thu, Jul 20, 2023

C++访问成员模板需要加template关键字

 1#include <iostream>
 2using namespace std;
 3
 4class A {
 5public:
 6	template <typename TypeNum>
 7	int getSize()
 8	{
 9		return sizeof(TypeNum);
10	}
11};
12
13// 调用成员模板函数需要加template
14template <typename T>
15void f1()
16{
17	T t1;
18	cout << (t1.template getSize<float>()) << endl;
19	cout << (t1.template getSize<double>()) << endl;
20}
21
22// 调用成员模板函数不需要加template
23void f2()
24{
25	A a1;
26	cout << (a1.getSize<long>()) << endl;
27	cout << (a1.getSize<long long>()) << endl;
28}
29
30int main()
31{
32	f1<A>();
33	f2();
34
35	return 0;
36}