-
总览
-
相同点
-
模板别名
-
using
#include<iostream> #include<vector> template<typename T> using Myvector = std::vector<T>; int main() { Myvector<int> b{1,2,3}; for(const auto& a : b) { std::cout << a << std::endl; } }
-
typedef
模仿#include<iostream> #include<vector> template<typename T> typedef std::vector<T> Myvector; int main() { Myvector<int> b{1,2,3}; for(const auto& a : b) { std::cout << a << std::endl; } }
-
改改
typedef
#include<iostream> #include<vector> template<typename T> struct Myvector { typedef std::vector<T> type; }; int main() { Myvector<int>::type b{1,2,3}; for(const auto& a : b) { std::cout << a << std::endl; } }
-
-
别名类型做成员变量
-
using
#include<iostream> #include<vector> template<typename T> using Myvector = std::vector<T>; template<typename T> class Temp { public: Myvector<T> a; }; int main() { Temp<int> b{{1,2,3}}; for(const auto& a : b.a) { std::cout << a << std::endl; } }
-
typedef
#include<iostream> #include<vector> template<typename T> typedef std::vector<T> Myvector; template<typename T> class Temp { public: Myvector<T> a; }; int main() { Temp<int> b{{1,2,3}}; for(const auto& a : b.a) { std::cout << a << std::endl; } }
-
typedef
改改版#include<iostream> #include<vector> template<typename T> struct Myvector { typedef std::vector<T> type; }; template<typename T> class Temp { public: Myvector<T>::type a; }; int main() { Temp<int> b{{1,2,3}}; for(const auto& a : b.a) { std::cout << a << std::endl; } }
-
可行版
typedef
#include<iostream> #include<vector> template<typename T> struct Myvector { typedef std::vector<T> type; }; template<typename T> class Temp { public: typename Myvector<T>::type a; }; int main() { Temp<int> b{{1,2,3}}; for(const auto& a : b.a) { std::cout << a << std::endl; } }
-
小结
-
小疑问
Myvector<T>::type
如果是类型,Myvector<T>::type()
就是匿名对象创建,调用默认构造.或者是函数声明?Myvector<T>::type
如果是变量名,恰好是个可调用对象,那么就是匿名返回值. 无法解析.语义都不一样了.
-
-
为什么不增强
typedef
的功能 -
C++
标准库的实现-
type_traits
-
获取某个类型的普通版本变量
#include <iostream> #include <type_traits> int main() { const int a = 0; std::remove_const<decltype(a)>::type b; b = 1; return 0; }
-
using
版本#include <iostream> #include <type_traits> template <typename T> using remove_const_t = typename std::remove_const<T>::type; int main() { const int a = 0; remove_const_t<decltype(a)> b; b = 1; return 0; }
-
typedef
-
type_traits
-
-
总结