samedi 4 juillet 2015

Capture an object's internal scope for use in a function

I have a customised vector container, and I'd like to give it a method which will return a list of all the elements which fulfil some condition. In fact, I've already done the hard part using some template tomfoolery which is outside the scope of this question; all I'd like to do from here is to simplify the syntax for the user.

To cut to the chase, my custom_vector<T> method's signature is:

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

and a typical use case is:

// 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; });

Now this works absolutely fine and does exactly what I want but it's ugly; on that last line I had to type "myVector" four times, when it should be perfectly obvious after the first one which closure I want to work within. What I really want is to be able to type:

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

or even better

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

...but I can't figure out a way of achieving this or even getting close to it. Is there one, or am I just going to have to put up with doing a lot of typing?

As this doesn't seem like so outlandish a thing to want to do, I'd be even more pleased if someone can point me to way of doing this with the STL; I've looked hard but so far failed to find anything.

Aucun commentaire:

Enregistrer un commentaire