对于 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
动机:
现在可以将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
版本begin
并end
为指针工作,但我做不到。所以我决定明确类型并删除所有模板:
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
到底是怎么回事?是否有一种编译器魔法禁止范围循环为指针工作。我是否对范围循环语法做出了错误的假设?
具有讽刺意味的是,在标准中有一个过载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
。