2
#include <array>
#include <functional>

template<typename T, typename ... Args>
auto make_array(T&& t, Args&& ... args) -> std::array<T, sizeof...(Args)+1> {
    return {std::forward<T>(t), std::forward<Args>(args)...};
}

int main() {
    auto f = [](int i)->int { return i; };
    auto f2 = [](int i)->int { return i*2; };

    auto arr2 = make_array<std::function<int(int)>>(f, f2);

    return 0;
}

Is there a way to not specify the template type at call site make_array<std::function<int(int)>> ?

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145

1 Answers1

3

It is possible to let the parameter type be deduced. With this clever solution by ecatmur you can automatically generate the proper std::function<> object:

template<typename T, typename ... Args>
auto make_array(T&& t, Args&& ... args) -> 
    std::array<make_function_type<T>, sizeof...(Args)+1>
//             ^^^^^^^^^^^^^^^^^^^^^
{
    return {std::forward<T>(t), std::forward<Args>(args)...};
}

#include <iostream>

int main() 
{
    auto f = [](int i)->int { return i; };
    auto f2 = [](int i)->int { return i*2; };

    auto arr2 = make_array(f, f2);
    std::cout << arr2[1](21); // Prints 42

    return 0;
}

Here is a live example.

Community
  • 1
  • 1
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451