Is it possible to return a variadic lambda from a function template?
Asked Answered
K

3

17

I have the following piece of code (c++11):

template <typename F,
          typename FirstT,
          typename... FIn>
auto min_on(F f, FirstT first, FIn... v) -> typename std::common_type<FirstT, FIn...>::type
{
  using rettype = typename std::common_type<FirstT, FIn...>::type;
  using f_rettype = decltype(f(first));

  rettype result = first;
  f_rettype result_trans = f(first);
  f_rettype v_trans;
  (void)std::initializer_list<int>{
      ((v_trans = f(v), v_trans < result_trans)
           ? (result = static_cast<rettype>(v), result_trans = v_trans, 0)
           : 0)...};
  return result;
}

Which basically returns the argument result that produced the minimum value for expression f(result). This can be called like this:

auto mod7 = [](int x)
{
    return x % 7;
};

auto minimum = min_on(mod7, 2, 8, 17, 5);
assert( minimum == 8); // since 8%7 = 1 -> minimum value for all arguments passed

Now I would like to use this in a 'curried' way so that I can get a variadic lambda from min_on and then call it with arguments (that I might receive later), like so:

auto mod7 = [](int x)
{
    return x % 7;
};

auto f_min = min_on(mod7);
auto minimum = f_min(2, 8, 17, 5);
// or 
auto minimum = min_on(mod7)(2, 8, 17, 5);

Is this even possible?

Kowloon answered 21/6, 2016 at 11:54 Comment(2)
Do you require C++11 only?Dualism
@Yakk yes, but you can mention C++14 solutions as wellKowloon
U
13

In C++11, the following works if you’re willing to manually create the function object:

template <typename F>
struct min_on_t {
    min_on_t(F f) : f(f) {}

    template <typename T, typename... Ts>
    auto operator ()(T x, Ts... xs) -> typename std::common_type<T, Ts...>::type
    {
        // Magic happens here.
        return f(x);
    }

    private: F f;
};

template <typename F>
auto min_on(F f) -> min_on_t<F>
{
    return min_on_t<F>{f};
}

And then call it:

auto minimum = min_on(mod7)(2, 8, 17, 5);

To use lambdas in C++14, you need to omit the trailing return type because you cannot specify the type of the lambda without assigning it to a variable first, because a lambda expression cannot occur in an unevaluated context.

template <typename F>
auto min_on(F f)
{
    return [f](auto x, auto... xs) {
        using rettype = std::common_type_t<decltype(x), decltype(xs)...>;
        using f_rettype = decltype(f(x));

        rettype result = x;
        f_rettype result_trans = f(x);
        (void)std::initializer_list<int>{
          (f(xs) < result_trans
               ? (result = static_cast<rettype>(xs), result_trans = f(xs), 0)
               : 0)...};
        return result;
    };
}
Unremitting answered 21/6, 2016 at 12:10 Comment(3)
It is possible to return variadic lambda from a function in C++14: just omit trailing return type - it will be deduced.Kolinsky
@Kolinsky Duh, of course. I always forget about that.Unremitting
@KonradRudolph + additionally in C++14 you can use std::common_type_t. Please mark explicitly the first solution as C++11 so that people can see the differences in the 2 approaches.Kowloon
K
6

Not sure on C++11, but in C++14, you could create a lambda to wrap your function in:

auto min_on_t = [](auto f) {
    return [=](auto ... params) {
        return min_on(f, params...);
    };
};

auto min_t = min_on_t(mod7);
auto minimum = min_t(2, 8, 17, 5);

Live on Coliru

Kiarakibble answered 21/6, 2016 at 12:47 Comment(1)
Note that this auto arg feature is well supported even on mostly C++11 compilers.Dualism
D
3

In C++14 this is easy.

template<class F>
auto min_on( F&& f ) {
  return [f=std::forward<F>(f)](auto&& arg0, auto&&...args) {
    // call your function here, using decltype(args)(args) to perfect forward
  };
}

Many compilers got auto return type deduction and arguments in lambdas working prior to full C++14 support. So a nominal C++11 compiler might be able to compile this:

auto min_on = [](auto&& f) {
  return [f=decltype(f)(f)](auto&& arg0, auto&&...args) {
    // call your function here, using decltype(args)(args) to perfect forward
  };
}

in C++11:

struct min_on_helper {
  template<class...Args>
  auto operator()(Args&&...args)
  -> decltype( min_on_impl(std::declval<Args>()...) )
  {
    return min_on_impl(std::forward<Args>(args)...);
  }
};

is boilerplate. This lets us pass the entire overload set of min_on_impl around as one object.

template<class F, class T>
struct bind_1st_t {
  F f;
  T t;
  template<class...Args>
  typename std::result_of<F&(T&, Args...)>::type operator()(Args&&...args)&{
    return f( t, std::forward<Args>(args)... );
  }
  template<class...Args>
  typename std::result_of<F const&(T const&, Args...)>::type operator()(Args&&...args)const&{
    return f( t, std::forward<Args>(args)... );
  }
  template<class...Args>
  typename std::result_of<F(T, Args...)>::type operator()(Args&&...args)&&{
    return std::move(f)( std::move(t), std::forward<Args>(args)... );
  }
};
template<class F, class T>
bind_1st_t< typename std::decay<F>::type, typename std::decay<T>::type >
bind_1st( F&& f, T&& t ) {
  return {std::forward<F>(f), std::forward<T>(t)};
}

gives us bind_1st.

template<class T>
auto min_on( T&& t )
-> decltype( bind_1st( min_on_helper{}, std::declval<T>() ) )
{
  return bind_1st(min_on_helper{}, std::forward<T>(t));
}

is modular and solves your problem: both min_on_helper and bind_1st can be tested independently.

You can also replace bind_1st with a call to std::bind, but in my experience the quirks of std::bind make me extremely cautious about recommending that to anyone.

Dualism answered 21/6, 2016 at 13:56 Comment(5)
Why the difference from C++14 to C++1z?Runnerup
@Runnerup because the crappy compiler I did much C++14 work on didn't have auto return types when it had much of C++14 implemented. Edited versions.Dualism
Shouldn't that decltype( min_on_impl(std::declval<Args>()...) be decltype( min_on_impl(std::forward<Args>(args)...), the decltype should be forward to match the actual call? It could produce errors if there are overloads that vary on the lvalue/rvalue-ness of the parameters.Carlottacarlovingian
@Carlottacarlovingian The return type of std::declval<Args>() is the same as std::forward<Args>(args). std::declval<Args>() is shorter. I am lazy.Dualism
The forgotten reference collapsing. Keep thinking of declval as an rvalue return only ... They are the same return.Carlottacarlovingian

© 2022 - 2024 — McMap. All rights reserved.