捕获对象的内部作用域以在函数中使用

时间:2015-07-04 09:15:29

标签: c++ c++11 lambda scope closures

我有一个自定义的矢量容器,我想给它一个方法,它将返回满足某些条件的所有元素的列表。事实上,我已经完成了使用一些模板tomfoolery的困难部分,这超出了这个问题的范围;我想从这里做的就是简化用户的语法。

要切入追逐,我的custom_vector< T>方法的签名是:

custom_vector<int> where(std::function< bool (int) > predicate) const;

一个典型的用例是:

// Find all the elements of myVector which lie between 2.71828 and 3.14159
custom_vector<int> theListOfElementsIWant =
    myVector.where([&myVector](int i) { return myVector.at(i)>2.71828 &&  myVector.at(i)<3.14159; });

现在这个工作绝对正常,完全符合我的要求,但它的丑陋;在最后一行,我必须键入&#34; myVector&#34;四次,当我想在其中工作的第一个关闭之后它应该是非常明显的。我真正想要的是能够输入:

custom_vector<int> theListOfElementsIWant = 
    myVector.where([](int i) { return at(i)>2.71828 && at(i)<3.14159; });  

甚至更好

custom_vector<int> theListOfElementsIWant = myVector.where(at(i)>2.71828 && at(i)<3.14159);

...但我无法找到实现这一目标的方法,甚至无法接近它。有没有,或者我只是不得不忍受做很多打字?

由于这似乎不是一件令人头疼的事情,如果有人能指出我用STL这样做的话,我会更高兴。我看起来很难,但到目前为止都找不到任何东西。

1 个答案:

答案 0 :(得分:1)

我建议传递元素而不是索引:

custom_vector<T> where(std::function<bool (const T&)> predicate) const;

用法:

custom_vector<double> theListOfElementsIWant = 
    myVector.where([](double e) { return 2.71828 < d && d < 3.14159; });