为什么要在 C++ 标准容器中为模板参数添加别名?

Dra*_*son 2 c++ templates class std type-alias

回顾微软的STL的代码(具体来说std::vector),我发现了以下几行代码(无关代码替换为/* ... */):

// CLASS TEMPLATE vector
template <class _Ty, class _Alloc = allocator<_Ty>>
class vector // varying size array of values
{ 
    /* ... */
public:

   /* ... */
   using value_type = _Ty;
   using allocator_type = _Alloc;
   using pointer = typename _Alty_traits::pointer;
   using const_pointer = typename _Alty_traits::const_pointer;
   using reference = _Ty&;
   using const_reference = const _Ty&;
   using size_type = typename _Alty_traits::size_type;
   using difference_type = typename _Alty_traits::difference_type;
   /* ... */
};
Run Code Online (Sandbox Code Playgroud)

我想知道为什么这里使用为模板类型分配类型别名的约定?

max*_*x66 5

我想知道为什么这里使用为模板类型分配类型别名的约定?

假设您有一个接受 STL 容器的模板函数(std::vector, std::deque, std::set, std::multi_set, ...)

template <typename T>
void foo (T const & t)
 {
   // ...
 }
Run Code Online (Sandbox Code Playgroud)

并且您需要包含值的类型。

你可以在里面foo()简单地写

 using needed_type = typename T::value_type;
Run Code Online (Sandbox Code Playgroud)

这适用于std::vector, std::deque, std::set, std::multi_set, std::array, std::map,std::multi_map等。