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)>> ?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.