通过容器(数组)类型萃取元素类型范例
【用GetEleType类模板进行常规实现】
//泛化版本 template <typename T> struct GetEleType; //特化版本 template <typename T> struct GetEleType<std::vector<T>> { using type = T; }; template <typename T> struct GetEleType<std::list<T>> { using type = T; }; template <typename T,std::size_t Size> //这个特化版本增加了一个模板参数 struct GetEleType<T[Size]> //萃取出数组元素个数 //技巧:由T[Size]反推类型为 typename T,std::size_t Size //T[Size]视为一个参数类型,其泛化版本只有一个类型。 { using type = T; static const std::size_t size = Size; };
- 调用
cout << "vector<double>的元素类型为:" << typeid(GetEleType< vector<double> >::type).name() << endl; cout << "list<int>的元素类型为:" << typeid(GetEleType< list<int> >::type).name() << endl; cout << "float[45]的元素类型为:" << typeid(GetEleType< float[45] >::type).name() << endl; cout << "float[45]的数组元素数量为:" << GetEleType< float[45] >::size << endl;
- 输出
【引入函数模板PrintEleType】
//函数模板 template <typename T> void PrintEleType(const T& container) { cout << "容器(数组)的元素类型为:" << typeid(GetEleType<T>::type).name() << endl; }
- 调用
vector<double> mydblvec; PrintEleType(mydblvec); list<int> myintlist; PrintEleType(myintlist); float myfloatarr[45]; PrintEleType(myfloatarr);
- 输出
【GetEleType类模板的改进】
//泛化版本,用泛化版本实现对容器类型的支持 template <typename T> struct GetEleType { using type = typename T::value_type; //针对容器 }; //针对数组的特化版本(内容不变) template <typename T, std::size_t Size> //这个特化版本增加了一个模板参数 struct GetEleType<T[Size]> //萃取出数组元素个数 { using type = T; static const std::size_t size = Size; }; //别名模板: template <typename T> using EleType = typename GetEleType<T>::type; //函数模板 template <typename T> void PrintEleType(const T& container) { cout << "容器(数组)的元素类型为:" << typeid(EleType<T>).name() << endl; }
- 调用
vector<double> mydblvec; PrintEleType(mydblvec); list<int> myintlist; PrintEleType(myintlist); float myfloatarr[45]; PrintEleType(myfloatarr);
- 输出