C ++什么时候标准库容器中的typedef不是你所期望的?

时间:2014-10-23 15:20:55

标签: c++ c++11 stl

对于哪些标准库容器类型是容器中的typedef而不是你天真想到的?

在代码中,T类型和容器container_type上的条件执行以下静态检查,而不是全部评估为true:

typedef double T;
typedef std::vector<T> container_type;

std::is_same<typename container_type::value_type, T>::value; 
std::is_same<typename container_type::reference, T&>::value; 
std::is_same<typename container_type::const_reference, T const&>::value; 
std::is_same<typename container_type::pointer, T*>::value;  
std::is_same<typename container_type::const_pointer, T const*>::value;  

我只知道std::vector<bool>::reference不是bool&(可能const版本也是如此)。

还有其他人吗?

1 个答案:

答案 0 :(得分:6)

对于包含T类型对象的任何容器,标准(C ++ 11 23.2.1 / 4)要求:

  • container_type::value_typeT
  • container_type::referenceT的左值,即T&
  • container_type::const_referenceT的限制值,即const T&

pointerconst_pointer不是任何Container要求的一部分,它们只是标准容器中的便捷typedef,取自容器的分配器。

所以,回答你的问题:

value_typereferenceconst_reference必须符合您的预期,否则容器不符合Container要求。请注意,这意味着(例如Herb Sutter points out),std::vector<bool> 不是标准意义上的容器。

pointerconst_pointer是分配器类型的typedef,因此当您有一个带分配器A的容器时,它们将与T*T const*不同只要std::allocator_traits<A>::pointerstd::allocator_traits<A>::const_pointer与他们不同。

直接解决哪些标准容器满足这些Container要求的问题:

  • std::array<T>符合23.3.2.1/3(有一些例外情况不会影响相关的typedef)
  • std::deque<T>按照23.3.3.1/2
  • 执行
  • std::forward_list<T>按照23.3.4.1/2执行(有一些例外情况不会影响相关的typedef)
  • std::list<T>符合23.3.5.1/2
  • std::vector<T>按照T除了bool之外的每个23.3.6.1/2(有一些例外情况不会影响相关的typedef)
  • std::set<T>符合23.4.6.1/2
  • std::multiset<T>根据23.4.7.1/2
  • 执行
  • std::unrdered_set<T>,按照23.5.6.1/2
  • std::unordered_multiset<T>,按照23.5.7.1/2
  • std::basic_string<T>按照21.4./5包含有问题的typedef(到正确的类型),即使标准没有明确要求它满足Container要求。请注意,value_type取决于角色特征,因此std::basic_string<T, MyTraits>可以value_type以外的T

std::[unorderd_][multi]map不具备资格,因为他们会使用多个必填模板参数并使用它们来合成value_type

std::valarray<T>不符合条件,因为它只提供value_type typedef而不提供其他类型。

相关问题