具有代理迭代器/引用和自动的容器

问题描述 投票:7回答:2

我正在使用与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...

EDIT:重新编写了示例以使其更加清晰。感谢@LucDanton在下面的评论。

c++ c++11 iterator generic-programming c++14
2个回答
3
投票
与主要模板vector<bool>相比,

众所周知,vector<T>具有非通用接口


3
投票
代理和auto不能很好地交互,正是因为auto揭示了有关应该隐藏的类型的东西。
© www.soinside.com 2019 - 2024. All rights reserved.