Search code examples
c++templatesc++11lambdac++14

Lambda function with number of arguments determined at compile-time


I would like to declare a lambda function with exactly N parameters, where N is a template argument. Something like...

template <int N>
class A {
    std::function<void (double, ..., double)> func;
                        // exactly n inputs
};

I could not think of a way to do this with the metafunction paradigm.


Solution

  • You can write a template n_ary_function with a nested typedef type. This type can be used as follows:

    template <int N>
    class A {
        typename n_ary_function<N, double>::type func;
    };
    

    The following code fragment contains the definition of n_ary_function:

    template <std::size_t N, typename Type, typename ...Types>
    struct n_ary_function
    {
        using type = typename n_ary_function<N - 1, Type, Type, Types...>::type;
    };
    
    template <typename Type, typename ...Types>
    struct n_ary_function<0, Type, Types...>
    {
        using type = std::function<void(Types...)>;
    };