Lambdas and std::function

前端 未结 2 811
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 02:21

I\'m trying to catch up on C++11 and all the great new features. I\'m a bit stuck on lambdas.

Here\'s the code I was able to get to work:

#include &         


        
2条回答
  •  一整个雨季
    2020-12-04 02:53

    As has been revealed by other posters, this is a template argument deduction for std::function.

    One intuitive way to make the second code snippet work is to add your base type when calling the template function: findMatches.

    Another way not mentioned by Xeo is using std::is_convertible:

    template
    vector findMatches(vector search, function  func)
    {
        static_assert(std::is_convertible >::value, "func must be convertible to ...");
    
        vector tmp;
    
        for(auto item : search)
        {
            if( func(item) )
            {
                tmp.push_back(item);
            }
        }
    
        return tmp;
    }
    

    It avoids wrapping lamda into std::function, and provides a cleaner error message.

提交回复
热议问题