template<class> 作用
最近看了一下 STL,在 vector 里发现了 template<class> 这样一条语句,请问有什么作用呢?这句代码在 链接: https://pan.baidu.com/s/1i5_LIhC4H_OplQPZFHsu7g 提取码: 9kfc 的 414 行。 举个例子
#include <cstdio>
#include <Windows.h>
// template函数
template<class T>
T add(T a, T b)
{
return (T)(a + b);
}
// template类
template<class Type>
class Data
{
public:
Data(Type d)
{
data = d;
}
Type GetData()
{
return data;
}
private:
Type data;
};
int main()
{
int n = add<int>(2, 4); // 此时T相当于int
double f = add<double>(1.4, 3.5); // 此时T相当于double
printf("%d\n", n); // 输出:6
printf("%f\n", f); // 输出:4.9
// template还可以进行类型推断
n = add(2, 4); // 因为2和4都是int,所以编译器自动认为T就是int
printf("%d\n", n); // 输出:6
Data<int> nData(3);
printf("%d\n", nData.GetData()); // 输出:3
Data<double> fData(6.5);
printf("%f\n", fData.GetData()); // 输出:6.5
system("pause");
return 0;
} lhgzbxhz 发表于 2020-7-15 11:27
举个例子
那是个空的模板……我是想知道空模板有什么作用{:10_277:} 永恒的蓝色梦想 发表于 2020-7-15 11:46
那是个空的模板……我是想知道空模板有什么作用
举个例子:
#include <cstdio>
#include <string>
#include <Windows.h>
using namespace std;
template<class T>
T add(T a, T b)
{
return (T)(a + b);
}
template<>
string add(string a, string b) // string的add方法和其它add方法不一样
{
string temp = a;
temp.append(b);
return temp;
}
int main()
{
int n = add(1, 2);
string s1("he"), s2("ge");
string s = add(s1, s2);
printf("%s\n", s.c_str());
system("pause");
return 0;
} 可以百度一下“模板专门化”是什么 lhgzbxhz 发表于 2020-7-15 12:03
可以百度一下“模板专门化”是什么
谢谢您的回答。
源代码中是这样的: template <class>
friend class _Vb_val;
friend _Tidy_guard<vector>;并没有模板函数,这有什么作用呢? emmm...刚刚看了看,刚刚说错了,抱歉
不过VC的vector里好像没有这行代码 lhgzbxhz 发表于 2020-7-15 12:10
emmm...刚刚看了看,刚刚说错了,抱歉
不过VC的vector里好像没有这行代码
额,这里是 Visual Studio 2019 的 vector 。
不过你的回答也解决了我的一些疑问。还是很感谢! 永恒的蓝色梦想 发表于 2020-7-15 12:12
额,这里是 Visual Studio 2019 的 vector 。
不过你的回答也解决了我的一些疑问。还是很感谢!
我查了一下,这好像是C++14中引入的变量模板
我也不是很懂,但我写了这样一段代码:
#include <cstdio>
#include <Windows.h>
using namespace std;
template<class> int var;
int main()
{
var<int> = 3;
var<double> = 4.5;
printf("%d\n", var<int>); // 输出:3
printf("%f\n", var<double>); // 输出:4.5
system("pause");
return 0;
} 永恒的蓝色梦想 发表于 2020-7-15 12:12
额,这里是 Visual Studio 2019 的 vector 。
不过你的回答也解决了我的一些疑问。还是很感谢!
等等,这好像不是变量模板
template<class T>
class A
{
public:
A(T d)
{
data = d;
}
private:
T data;
};
template<class T>
class B
{
template<class> friend class A;
//... 其它函数
}; 这貌似只是friend class的声明,只是一个模板类声明而已
页:
[1]