LaVOZs

The World’s Largest Online Community for Developers

'; c++ - std::function template argument deduction - LavOzs.Com

I have created a example my current problem. I want to be able to able to call the following function without specifying the template type since the compiler should be able to find out the type:

template<typename T, class Iterable>
void foreach1(std::function<void(T&)> action, Iterable& iterable) {
    std::cout << typeid(T).name() << std::endl;
    for (auto& data : iterable)
        action(data);
}

If i call the function this way:

std::vector<int> a = { 1, 2, 3 };
foreach1([](int& data) {
    std::cout << data << std::endl;
}, a);

I get an error. I know that i could fix the problem by replacing std::function with a template the following way:

template<class Action, class Iterable>
void foreach2(Action action, Iterable& iterable) {
//std::cout << typeid(T).name() << std::endl; // no access to T
for (auto& data : iterable)
    action(data);
}

But by doing that i lose access to the type T. Is there a way of keeping access to the type T and be able to use template argument deduction?

Implicit conversions are not allowed when passing arguments to parameters whose types depend on deduced template parameters.

I suggest using the second option:

template<class Action, class Iterable>
void foreach2(Action action, Iterable& iterable)

And to determine T, start with making a std::function out of action:

std::function(action)

Then write a template to get the type of the parameter of a std::function:

template <typename T> struct std_func_param {};
template <typename R, typename T> struct std_func_param<std::function<R(T)>> {using type = T;};
template <typename T> using std_func_param_t = typename std_func_param<T>::type;

Use it like this:

using T = std_func_param_t<decltype(std::function(action))>;
Related
Why can templates only be implemented in the header file?
Where and why do I have to put the “template” and “typename” keywords?
Why is the C++ STL is so heavily based on templates? (and not on *interfaces*)
Function passed as template argument
Why is “using namespace std;” considered bad practice?
Pretty-print C++ STL containers
template argument deduction/substitution failed, when using std::function and std::bind
Nested template argument deduction for class templates not working
Type aliases and template template argument deduction
Function template argument deduction (class vs funtion template)