Dolfos
Dolfos

Reputation: 58

std::function template argument deduction

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?

Upvotes: 2

Views: 237

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96013

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

Upvotes: 3

Related Questions