(二十八)C++篇-template(一)

我们可以不用为每个类型定义一个新函数,而是只定义一个函数模板(function template)。函数模板是一个独立于类型的函数,可作为一种方式,产生函数的特定类型版本。例如,可以编写名为 compare 的函数模板,它告诉编译器如何为我们想要比较的类型产生特定的 compare 版本。

测试代码:

#include
#include

using namespace std;

template 
int compare(const T &v1, const T &v2)
{
    if (v1 < v2) return -1;
    if (v2 < v1) return 1;
    return 0;
}

int main(void)
{
    //int result = compare(5,10);
    string a = "b";
    string b = "a";
    int result = compare(a,b);
    cout<<"result: "<

输出结果:

tekken@tekken:~/C++WS$ ./a.out 
result: 1

练习:编写一个函数模板,接受一个 ostream 引用和一个值,将该值写入流。用至少四种不同类型调用函数。通过写至cout、写至文件和写至 stringstream 来测试你的程序。

测试代码:

#include
#include
#include
#include

using namespace std;

template
T1& print(T1& s,T2 val)
{
    s<

输出结果:

tekken@tekken:~/C++WS$ ./a.out 
-3
0.88
-12.3
this is a test
-3
0.88
-12.3
this is a test

你可能感兴趣的:((二十八)C++篇-template(一))