c++ template怎么使用及注意事项

c++ 中的template和c#的什么有点相似?

先看下定义方式:

template <typename|class T>
T myFunction(T param1,T param2...)
{
        T result= param1;
        // do something  

        return result;  
}

一看到这个定义方式,就想起来c#中的泛型:

List<T>
List<int> item=new List<int>();
KeyValuePair<T,T>
Dictionary<T,T>
Dictionary<int,string> dict=new Dictionary<int,string>();
Func<in T...,out T>
Action<in T...,out void>
&&

其实,他们的用法和作用上都是很相似的.

使用之前,我们先看下使用注意事项:

1.如果你新建的工程是分空Console,请注意要把#include "stdafx.h"放在文件(头文件,资源文件)第一行,否则,不管是模板还是其他都地方都会编译失败;

2.使用模板时,template<typename|class T> 声明行同使用T的函数之间不允许出现其他代码行,最好也不要空行(没有验证有空行是否会编译失败)。

使用示例

工程文件结构:

注:

Templates.h---模板定义

ConsoleApplication1.cpp---main入口函数文件

Templates.h中代码:

#include "stdafx.h"

#include <iostream>

template< class T > 
T myFunc(T first,T second,T third)
{
    T maxValue=first;

    if(second>maxValue)
    {
        maxValue=second;
    }

    if(third>maxValue)
    {
        maxValue=third;
    }

    return  maxValue;
};

ConsoleApplication1.cpp 调用代码:

#include "stdafx.h"

#include <iostream>
using std::cout;
using std::endl;

#include <conio.h>
#include "Templates.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int maxValue=myFunc(1,3,10);

    cout<<"gradeBook1 created for course:"<< endl;
    cout<< "The max value is:"<<maxValue<< endl;
    std::cin.get();
    return 0;
}

输出结果:

原文地址:https://www.cnblogs.com/yy3b2007com/p/3722060.html