zoukankan      html  css  js  c++  java
  • 【C/C++】【模板和泛型】using定义模板别名

    using定义模板别名

    1. using

      //typedef:一般用来定义类型别名
      typedef unsigned int uint_t;
      uint_t abc;
      //map<string, int>
      typedef map<string, int> hashmap;
      
      hashmap m;
      m.insert({ "first", 1 });
      
      //map<string, string>
      typedef map<string, string> hashmap_ss;
      
    2. 定义一个map类型,key是string类型,不变,value的类型可以自己指定

    • C++98

      #include <iostream>
      #include <map>
      #include <string>
      using namespace std;
      
      //c++98
      template <typename st>
      struct map_s //定义了一个结构;结构成员的缺省都是public
      {
      	typedef map <string, st> type;//定义了一种类型
      };
      
      
      int main()
      {
      	map_s<int>::type map;
      	return 0;
      }
      
    • C++11

      #include <iostream>
      #include <map>
      #include <string>
      using namespace std;
      
      //C++11
      template <typename T>
      using str_map = map<string, T>; //str_map是类型别名
      //using 给模板起别名 用来给“类型模板”起名字
      //using用于定义类型的时候,包含了typedef的所有功能
      int main()
      {
      	str_map<int> map;
      	map.insert({ "abc", 123 });
      	return 0;
      }
      
    1. 函数指针模板

      typedef int(*FuncType)(int, int);
      using FuncType = int(*)(int, int);
      
      #include <iostream>
      #include <map>
      #include <string>
      using namespace std;
      
      template <typename T>
      using myfunc_M = int(*)(T, T); //定义类型模板 函数指针模板
      
      
      int RealFunc(int i, int j)
      {
      	cout << i + j << endl;
      	return 1;
      }
      
      int main()
      {
      	myfunc_M<int> pointFunc = RealFunc;
      	pointFunc(1, 2);
      	return 0;
      }
      

    显式指定模板参数

    #include <iostream>
    #include <map>
    #include <string>
    using namespace std;
    
    template <typename T1, typename T2, typename T3>
    T1 sum(T2 i, T3 j)
    {
    	T1 res = i + j;
    	return res;
    }
    
    int main()
    {
    	//自己指定的类型优先
    	auto res = sum<double>(2000000000000000000, 2000000000000000000);
    	cout << res << endl;
    	return 0;
    }
    
    //无法省略模板参数
    template <typename T1, typename T2, typename T3>
    T3 sum(T1 i, T2 j)
    {
    	T1 res = i + j;
    	return res;
    }
    
  • 相关阅读:
    3dsmax script export/import tools
    BOBO输出插件的一些信息
    任务
    说说谷歌在线电子表格
    EditGrid在线编辑Excel文档
    如何控制,textField的宽度,
    在线文档管理平台
    雅虎的这个效果,有机会实现一下
    推荐在线电子表格EditGrid
    我的台账录入界面
  • 原文地址:https://www.cnblogs.com/Trevo/p/14052686.html
Copyright © 2011-2022 走看看