引子
C++11中引入的std::unique_ptr
智能指针是个好用的东西,在我们使用unique_ptr
的时候往往会写出这样的类型std::uniqeu_ptr<std::unordered_map<std::string,std::string>>
,看上去很臃肿,因此大多数的时候我们会选择使用typedef
进行类型的重定义,简化类型名称。可是在C++11中引入了一个using
别名的机制,相比较而言引入这个机制会有其深层次的用意。本文就讨论一下using
的优势。
正文
首先看一个函数指针的例子:
typedef void (*FP)(int, const std::string&); // typedef
using FP = void (*)(int, const std::string&); // alias declaration
显然同样定义了函数指针FP
,using
可读性更强。
当然如果仅仅为了可读性,没必要引入一个新的机制。我们再看一个好的理由:using
可以定义模板别名(alias template),而typedef
则不能。例如,我们可以用using
直接定义一个通用的Allocator
例如:
template<typename T> // MyAllocList<T> is synonym for
using MyAllocList = std::list<T, MyAlloc<T>>; // std::list<T, MyAlloc<T>>
MyAllocList<Widget> lw; // client code
当然,我们也可以用typedef
实现上面的功能,但是由于tepedef
不能直接定义模板别名。故我们得把它放在一个模板类里面:
template<typename T> // MyAllocList<T>::type is synonym for
struct MyAllocList { // std::list<T, MyAlloc<T>>
typedef std::list<T, MyAlloc<T>> type;
};
MyAllocList<Widget>::type lw; // client code
这显然是非常不漂亮的,而且如果想把上面的模板别名用在模板类成员或者模板参数类型时,会非常不方便,需要使用typename
来告诉编译器:这是一个类型,而非类的静态成员或其他满足语法的情形。
template<typename T>
class Widget {
private:
typename MyAllocList<T>::type list;
...
};
但是,使用using
则无需这样:
template<typename T>
using MyAllocList = std::list<T, MyAlloc<T>>; // as before
template<typename T>
class Widget {
private:
MyAllocList<T> list; // no "typename", no "::type"
...
};
最后还有一个好处,模板别名using
可以在同时涉及到参数模板和函数模板时将两者关联起来做类型推导,而typedef
则不能。
template<typename T> // alias template from
using MyAllocList = std::list<T, MyAlloc<T>>; // Item 9 (PDF page 64)
template<typename T> // f1 is a function
void f1(MyAllocList<T>& list); // template
MyAllocList<Widget> lw; // also from Item 9
f1(lw); // fine, T in f1
// deduced as Widget
template<typename T> // struct with nested typedef
struct MyAllocList { // from Item 9 (PDF page 64)
typedef std::list<T, MyAlloc<T>> type;
};
template<typename T> // f2 is a function
void f2(typename MyAllocList<T>::type& list); // template
MyAllocList<Widget>::type lw; // also from Item 9
f2(lw); // error! can't
// deduce T in f2
在STL里面有用到using
模板别名的地方,即< type_traits >。在C++11和C++14中有:
std::remove_const<T>::type // C++11: const T → T
std::remove_const_t<T> // C++14 equivalent
std::remove_reference<T>::type // C++11: T&/T&& → T
std::remove_reference_t<T> // C++14 equivalent
std::add_lvalue_reference<T>::type // C++11: T → T&
std::add_lvalue_reference_t<T> // C++14 equivalent
而C++14中的实现就是用using
对C++11中进行模板别名包装得到的。
总结
1.
typedef
不支持类型模板化,但是using
的别名声明可以。
2.using
模板别名避免了typedef
有时涉及到的::type
后缀和typename
前缀。
3.C++14对C++11中某些模板函数使用到了模板别名。