将原始指针视为基于范围的for循环中的范围

时间:2015-01-30 18:10:41

标签: c++ pointers c++11 for-loop boost-optional

对于for-range循环语法,如何使原始指针的行为类似于范围。

double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;// will not execute if the pointer is null

动机:

现在,vox populi可以将boost::optional(未来std::optional)值视为范围,因此可用于范围循环http://faithandbrave.hateblo.jp/entry/2015/01/29/173613

当我重写我自己的简化版本时:

namespace boost {
    template <class Optional>
    decltype(auto) begin(Optional& opt) noexcept{
        return opt?&*opt:nullptr;
    }

    template <class Optional>
    decltype(auto) end(Optional& opt) noexcept{
        return opt?std::next(&*opt):nullptr;
    }
}

用作

boost::optional<int> opt = 3;
for (int& x : opt) std::cout << x << std::endl;

在查看代码时,我想象它也可以推广到原始(可空)指针。

double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;

而不是通常的if(dptr) std::cout << *dptr << std::endl;。哪个好,但我想实现上面的其他语法。

尝试

首先,我尝试将上述Optional版本的beginend用于指针,但我无法做到。所以我决定在类型中明确并删除所有模板:

namespace std{ // excuse me, this for experimenting only, the namespace can be removed but the effect is the same.
    double* begin(double* opt){
        return opt?&*opt:nullptr;
    }
    double* end(double* opt){
        return opt?std::next(&*opt):nullptr;
    }
}

几乎在那里,它适用于

for(double* ptr = std::begin(dptr); ptr != std::end(dptr); ++ptr) 
    std::cout << *ptr << std::endl;

但它不适用于所谓的等效 for-range循环:

for(double& d : dptr) std::cout << d << std::endl;

两个编译器告诉我:error: invalid range expression of type 'double *'; no viable 'begin' function available

发生了什么事?是否存在禁止ranged-loop为指针工作的编译器魔法。我是否对范围循环语法做出了错误的假设?

具有讽刺意味的是,在标准中,std::begin(T(&arr)[N])存在过载,这与它非常接近。


注意,第二个虽然

是的,这个想法很愚蠢,因为即使可能,这也会让人感到困惑:

double* ptr = new double[10];
for(double& d : ptr){...}

将仅迭代第一个元素。一个更清晰,更现实的解决方法是做一些像@Yakk提出的解决方法:

for(double& d : boost::make_optional_ref(ptr)){...}

通过这种方式,很明显我们只迭代一个元素,并且该元素是可选的。

好的,我会回到if(ptr) ... use *ptr

3 个答案:

答案 0 :(得分:7)

因为基于范围的作品的方式是(来自§6.5.4):

  

begin-expr end-expr 确定如下
   - 如果_RangeT是数组类型,[..]
   - 如果_RangeT是班级类型,[..]
   - 否则, begin-expr end-expr 分别为begin(__range)end(__range),其中begin   在关联的命名空间中查找end(3.4.2)。 [注意:普通的非限定查询(3.4.1)   没有执行。 -end note]

在这种情况下,相关的命名空间是什么? (§3.4.2/ 2,强调我的):

  

命名空间和类的集合以下列方式确定:
  (2.1) - 如果T是基本类型,其关联的命名空间和类集合都是空的

因此,没有地方可以放置double* begin(double*),以便基于范围的for语句调用它。

您想要做的只是制作一个简单的包装器的解决方法:

template <typename T> 
struct PtrWrapper {
    T* p;
    T* begin() const { return p; }
    T* end() const { return p ? p+1 : nullptr; }
};

for (double& d : PtrWrapper<double>{dptr}) { .. }

答案 1 :(得分:3)

认为通过“在ADL激活的上下文中调用for(:)std::begin来实现std::end循环是一个有用的谎言”。但这是谎言。

该标准基本上实现了std::beginstd::end的并行实现。这可以防止语言的低级构造依赖于它自己的库,这似乎是一个好主意。

该语言对begin的唯一查找是基于ADL的查找。除非您指向std::begin中的内容,否则将无法找到指针的std。编译器不会以这种方式找到std::begin( T(&)[N} ),而是通过语言对迭代进行硬编码。

namespace boost {
  template<class T>
  T* begin( optional<T>&o ) {
    return o?std::addressof(*o):nullptr;
  }
  template<class T>
  T* begin( optional<T&>&&o ) {
    return o?std::addressof(*o):nullptr;
  }
  template<class T>
  T const* begin( optional<T> const&o ) {
    return o?std::addressof(*o):nullptr;
  }
  template<class T>
  T* end( optional<T>&o ) {
    return o?std::next(begin(o)):nullptr;
  }
  template<class T>
  T* end( optional<T&>&&o ) {
    return o?std::next(begin(o)):nullptr;
  }
  template<class T>
  T const* end( optional<T> const&o ) {
    return o?std::next(begin(o)):nullptr;
  }
  template<class T>
  boost::optional<T&> as_optional( T* t ) {
    if (t) return *t;
    return {};
  }
}

现在你可以:

void foo(double * d) {
  for(double& x : boost::as_optional(d)) {
    std::cout << x << "\n";
}

无需重复double类型。

请注意,非参考的右值optional会返回T const*,而optonal的右值T&会返回T*。在写入上下文中迭代临时可能是一个错误。

答案 2 :(得分:0)

TL; DR

此构造可用于循环范围:

std::views::counted(raw_ptr, !!raw_ptr)

详细信息

C ++ 20使用 ranges库提供了多种创建临时可迭代项的方法。对于example

#include <ranges>
#include <iostream>
 
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    int *raw_ptr = a;
    
    for(int i : std::views::counted(raw_ptr, 10))
        std::cout << i << ' ';
    std::cout << '\n';
    
    for(int i : std::views::counted(raw_ptr, 1))
        std::cout << i << ' ';
    std::cout << '\n';
    
    std::cout << "empty for null pointer pointer\n";
    raw_ptr = nullptr;
    for(int i : std::views::counted(raw_ptr, 0))
        std::cout << i << ' ';
    std::cout << '\n';
    
    std::cout << "Exit\n";
}

打印

1 2 3 4 5 6 7 8 9 10 
1

empty for null pointer

Exit

类似地,std::views::subrange可以与(start,end]指针一起使用。检查library以获得更多信息。