samedi 26 décembre 2015

Capture C++11 lambda and preserving arguments

I would like to store an algorithm in a class.

template<typename TData>
class WhereParameters
{
public:
    explicit WhereParameters(const std::function<bool(TData)>& filter)
        : _filter(filter)
    {
    }

    explicit WhereParameters(std::function<bool(TData)>&& filter)
        : _filter(std::move(filter))
    {
    }

    std::function<bool(TData)>& Filter()
    {
      return _filter;
    }

private:
    std::function<bool(TData)> _filter;
};

The type is a template, so to find out the algorithm argument automatically I have made a template function.

template<typename TArgument>
auto Where(bool (*filterAlgo)(TArgument)) -> WhereParameters<TArgument>
{
    return WhereParameters<TArgument>(filterAlgo);
}

This does not compile

auto query111 = Where([](int data)->bool {return data>2;});

This compiles, however the reason why I made the template function was to avoid the manual specialization of the function template.

auto query111 = Where<int>([](int data)->bool {return data>2;});

What is the correct way to match a lambda (without closure) in a template function? I was trying around with the const keyword, but I just got another compilation error.

I also tried to put the lambda (which is in fact a function pointer) into the template class instead of std::function, but then I was unable to find out the argument type: I did not find a way to get some function traits working (this solution did not work for me).

Aucun commentaire:

Enregistrer un commentaire