【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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章