C++11中引入的 std::unique_ptr智能指针是个好用的东西,在我们使用 unique_ptr的时候往往会写出这样的类型 std::uniqeu_ptr
>,看上去很臃肿,因此大多数的时候我们会选择使用 typedef进行类型的重定义,简化类型名称。可是在C++11中引入了一个 using别名的机制,相比较而言引入这个机制会有其深层次的用意。
typedef void(*FP)(int,const std::string&);
using FP = void(*)(int,const std::string&);
看上去 using别名机制更加清晰,这或许是引入 using别名机制的原因之一吧。
template
using aliasList = std::list
; aliasList
li; template
struct aliasList { typedef std::list
type; }; aliasList
::type li;
typedef没有办法在模板声明的作用域中做类型重定义,必须放在一个自定义类型作用域内。而using没有这个限制除了上面提到的两点外 using还有一些其他的优点,比如对于嵌套类型来说不需要使用 typename。
template
class Widget {
private:
typename aliasList
::type list; };
使用 typedef定义的嵌套类型在模板中需要使用 typename,至于为什么可以参考cppreference
对于 using来说则不一样,因为使用了 using就不会有 ::type这样的后缀,因为这个后缀会让编译器迷惑这到底是类型还是成员变量,使用 using则避免了这个问题,因为没有 ::type,并且 aliasLitst
肯定是一个类型。尽管 using有以上诸多优点但是C++11中的 type_trais却大量用了 typedef,不过好在C++14中标准委员会认识到了 using是最好的方式并对C++11中的全部进行了替换。
std::remove_const
::type;
std::remove_reference
::type; std::add_lvalue_reference
::type;
到了C++14上面的 ::type都可以去掉了。