C++ alias template
type alias
type alias就是将某一个type重新命名为另一个更加直观简单的名字。C++中有两种type alias:
typedef
typedef [original-type] [your-alias];
比如:
typedef int Pixel;
Pixel p = 1; // 等价于 int p = 1;
typedef std::map<std::string, std::vector<std::string>> Map;
Map m; // 等价于std::map<std::string, std::vector<std::string>> m;
using
using [your-alias] = [original-type];
比如:
using Pixel = int;
Pixel p = 1; // 等价于int p = 1;
using Map = std::map<std::string, std::vector<std::string>>;
Map m;
typedef和using的区别
在这里,typedef和using都可以用来将int命名为Pixel,实现的功能是完全一样的。
但是,typedef不能和template一起使用。
比如当使用Map来创建instance的时候,只能创建类型为std::map<std::string, std::vector<std::string>>的Map,而不能创建类型为std::map<int, std::vector<int>>的Map,因为一开始就定义好了Map的类型。
Map m;// m can never be std::map<int, std::vector<int>>
如果想自定义传给std::map<>的类型,需要使用template,而只有using才可以使用template:
template<typename T1, typename T2>
using Map = std::map<T1, std::vector<T2>>;
Map<std::string, int> m1;
// std::map<std::string, std::vector<int>> m1;
Map<int, float> m2;
//std::map<int, std::vector<float>> m2;
alias template:
首先,假设有一个自定义的array类型,array的数据类型是T,默认是int,size是sz
template<auto sz, typename T = int>
struct Array{
T arr[sz];
};
template<auto sz, typename T = int>
using MyArray = Array<sz, T>
int main(){
MyArray<3>* arr1 = new Array<3>(); // Array with int type, size = 3
MyArray<3, double>* arr2 = new Array<3, double> // Array with double type, with size = 3;
}