我正在实现一个具有代理迭代器/引用类型的容器,类似于std :: vector< bool>并冲突到下面的问题,我继续举例说明std :: vector< bool> (这个问题不是关于std :: vector< bool>!):
#include <vector>
#include <type_traits>
int main() {
using namespace std;
vector<bool> vec = {true,false,true,false};
auto value = vec[2]; // expect: "vector<bool>::value_type"
const auto& reference = vec[2]; // expect: "vector<bool>::const_reference"
static_assert(is_same<decltype(value),vector<bool>::value_type>::value,"fails: type is vector<bool>::reference!");
static_assert(is_same<decltype(reference),vector<bool>::const_reference>::value,"fails: type is const vector<bool>::reference&!");
/// Consequence:
auto other_value = value;
other_value = false;
assert(vec[2] == true && "fails: assignment modified the vector");
>有没有办法实现代理类型,以便静态断言传递?
>在实施此类容器时,是否有关于如何处理此问题的指导原则?
也许通过使用转换运算符来auto / auto& / auto&& / const auto …?
编辑:重新设计示例以使其更清晰.感谢@LucDanton在下面的评论.
解决方法
代理和自动不能很好地交互,正是因为汽车揭示了应该隐藏的类型的事情.
有一半是对操作符自动风格的东西有兴趣(基本上,“当我把它作为一种类型推断时,改为使用这种类型”),但是AFAIK甚至没有将它作为官方提案.
另一个问题是矢量< bool>是意料之外的,因为它是使用代理的向量的唯一实例化.还有其他初步建议要求vector< bool>被弃用并最终恢复为非特殊的,引入了一个特殊用途的bitvector类来代替它.