Is std :: remove_if with a lambda predicate and auto element?

I assume this is not possible because I received the following error:

error C3533: 'auto': a parameter cannot have a type that contains 'auto' 

Here is a code snippet for reproducing the error:

 int myInts[] = {1,2,3,3,3,4}; std::vector<int> myVec(myInts, myInts + sizeof(myInts)/sizeof(int)); myVec.erase( std::remove_if(myVec.begin(), myVec.end(), [](auto i){return i==3;}), // lambda param error myVec.end()); 

Now, if you have to write this, everything will be fine, and it erases the elements with a value of 3:

 int myInts[] = {1,2,3,3,3,4}; std::vector<int> myVec(myInts, myInts + sizeof(myInts)/sizeof(int)); myVec.erase( std::remove_if(myVec.begin(), myVec.end(), [](int i){return i==3;}), myVec.end()); 

So, can you just not use auto as a function parameter, as the error shows?

Is it because the type auto is determined by the value r, which the compiler cannot infer, despite the fact that it is a predicate of an algorithm executed on the well-known vector int ?

Does anyone know the reason?

+6
source share
3 answers

Unfortunately, although this was suggested during the C ++ 0x process, it ultimately never did it. For simple functors, you can use something like Boost.Lambda (perhaps Phoenix v3 when it appears) where the created functors are polymorphic (and therefore you don't need to specify anything):

 std::remove_if(myVec.begin(), myVec.end(), _1 == 3) 

Solution with output type only:

 // uses pass-by-reference unlike the question std::remove_if(myVec.begin(), myVec.end(), [](decltype(myVec[0]) i){return i==3;}) 
+8
source

An auto is type inference based on the value you initialize. The parameter is not initialized by anything in the place that it is displayed in the code.

+8
source

In principle, this was already proposed, then rejected, and then lambdas were added, so he almost reached it, but this did not happen, and, most likely, it will turn into a language in the future.

+2
source

Source: https://habr.com/ru/post/890451/


All Articles