是否可以自定义 reference
的std::vector
。
在 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)
的返回类型到一个特殊的代理对象。
具体实现:我正在查看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?
目的是停止 promise 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
没有引用
自定义点。
关于c++ - 是否还可以自定义STL vector 的 "reference"类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41580521/