zoukankan      html  css  js  c++  java
  • 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;
    }

    输出结果:

  • 相关阅读:
    PHP使用Memcache来存储session 其他【转载】
    Linux 学习记录 20170218
    php 数组去重
    关于php的array_diff和array_diff_assoc的使用总结
    使用谷歌浏览器调试WEB前端的一些必备调试技巧
    MySql 赋值操作符"="与":="
    移动设备检测类Mobile_Detect.php
    PHP Filter 函数 日常可用
    以符合人类阅读的方式打印php数组【转载】
    JavaWeb:HttpSession(一)
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/3722060.html
Copyright © 2011-2022 走看看