是否仍然可以自定义 STL 矢量的 "reference" 类型?
Is it still possible to customize STL vector's "reference" type?
是否可以自定义 std::vector
的 reference
。
在 C++11 之前,似乎可以通过 Allocator
模板参数实现。
但现在不是了?
根据文档,http://en.cppreference.com/w/cpp/container/vector、reference
现在始终是 value_type
,而 value_type
始终是模板参数 T
。
即使使用allocator_traits
似乎也不可能,
http://en.cppreference.com/w/cpp/memory/allocator_traits
有解决办法吗?
如果不是,这是否意味着我必须专门化整个 std::vector
并且如果我想拥有一个基于分配器的特殊 reference
类型可能会重现它的所有功能?
如果是这样,一般来说所有这些限制的逻辑是什么?强制用户使用 std::vector<T, A>
始终管理常规内存(其中,value_type = T
、reference = T&
和 pointer = T*
?)
注意:我知道 std::vector<bool>
争议。然而这有点笼统,因为原则上我需要一个自定义 std::vector<RegularType, special_allocator<RegularType>>
主要是为了控制 operator[](int)
的 return 类型到一个特殊的代理对象。
具体实现:我在看GCC 6.3.1的stdlib源码,在std_vector.h
中可以看到:
template<typename _Tp, ...>
class vector : ...{
...
public:
typedef typename _Alloc_traits::reference reference;
};
这似乎表明仍然可以通过 allocator
指定引用类型(_traits
?)。
根据文档,allocator
或 allocator_traits
不需要 reference
类型。
另外,我不知道如何自定义这种类型。
GCC 没有遵循标准吗?或者只是间接地allocator_traits<Allocator>::reference
被强制为allocator_traits<Allocator>::value_type&
?
If this is so, generally speaking what is the logic for all these constrains?
目的是停止承诺 C++ 无法提供的东西。
在 C++98/03 时代,人们认为代理类型、专用引用等可以真正与标准库容器和算法一起工作。到 C++11 推出时,很明显……不,他们真的不能。或者至少,不具有与实际语言参考相同的语义。
考虑到这一点,C++11 删除了很多这些不再合理的定制点。保留了 typedef,但主要是为了向后兼容。
which seems to indicate that it is still possible to specify a reference type via the allocator (_traits?).
不,不是。这是 libstdc++ 中的错误; reference
现在对于容器 value_type&
是必需的。 allocator_traits
没有 reference
个自定义点。
是否可以自定义 std::vector
的 reference
。
在 C++11 之前,似乎可以通过 Allocator
模板参数实现。
但现在不是了?
根据文档,http://en.cppreference.com/w/cpp/container/vector、reference
现在始终是 value_type
,而 value_type
始终是模板参数 T
。
即使使用allocator_traits
似乎也不可能,
http://en.cppreference.com/w/cpp/memory/allocator_traits
有解决办法吗?
如果不是,这是否意味着我必须专门化整个 std::vector
并且如果我想拥有一个基于分配器的特殊 reference
类型可能会重现它的所有功能?
如果是这样,一般来说所有这些限制的逻辑是什么?强制用户使用 std::vector<T, A>
始终管理常规内存(其中,value_type = T
、reference = T&
和 pointer = T*
?)
注意:我知道 std::vector<bool>
争议。然而这有点笼统,因为原则上我需要一个自定义 std::vector<RegularType, special_allocator<RegularType>>
主要是为了控制 operator[](int)
的 return 类型到一个特殊的代理对象。
具体实现:我在看GCC 6.3.1的stdlib源码,在std_vector.h
中可以看到:
template<typename _Tp, ...>
class vector : ...{
...
public:
typedef typename _Alloc_traits::reference reference;
};
这似乎表明仍然可以通过 allocator
指定引用类型(_traits
?)。
根据文档,allocator
或 allocator_traits
不需要 reference
类型。
另外,我不知道如何自定义这种类型。
GCC 没有遵循标准吗?或者只是间接地allocator_traits<Allocator>::reference
被强制为allocator_traits<Allocator>::value_type&
?
If this is so, generally speaking what is the logic for all these constrains?
目的是停止承诺 C++ 无法提供的东西。
在 C++98/03 时代,人们认为代理类型、专用引用等可以真正与标准库容器和算法一起工作。到 C++11 推出时,很明显……不,他们真的不能。或者至少,不具有与实际语言参考相同的语义。
考虑到这一点,C++11 删除了很多这些不再合理的定制点。保留了 typedef,但主要是为了向后兼容。
which seems to indicate that it is still possible to specify a reference type via the allocator (_traits?).
不,不是。这是 libstdc++ 中的错误; reference
现在对于容器 value_type&
是必需的。 allocator_traits
没有 reference
个自定义点。