C++98/03:
在 C++ 中可以通过 typedef 重定义一个类型:typedef unsigned int uint_t;
但是无法重定义一个模板。所以不得不这么写:
template<typename Val>
struct str_map
{
typedef map<string, Val> type;
}
//使用
str_map<int>::type map1; //必须加个str_map<int>外敷类
C++11:
using别名语法它来了!它来了!
template<typename Val>
using str_map_t = map<string, Val>; //using重定义的即不是类模板也不是函数模板,也是一个模板别名
str_map_t<int> map1; //可以不用写str_map<int>::str_map_t<int> map1
总结:
普通类型的重定义对比:using比typedef语法更清晰。
// 重定义unsigned int
typedef unsigned int uint_t;
using uint_t = unsigned int;
// 重定义std::map
typedef map<string, int> map_int_t;
using map_int_t = map<string, int>;
看看新的using语法如何定义模板别名:
/* C++98/03 */
template <typename T>
struct func_t{
typedef void (*type)(T,T);
};
//使用func_t模板
func_t<int>::type xx_1;
/* C++11 */
template<typename T>
using func_t = void(*)(T,T); //using重定义的即不是类模板也不是函数模板,也是一个模板别名
//使用func_t模板
func_t<int> xx_2;