C++ Deduced Template Parameters

2018-06-08 ☼ codingc++

Kinda neat: the compiler is smart enough to automatically deduce some template parameters, but you only have to specify the ones that it can’t deduce. Those ones must come first. Makes sense.

Example:

template<class O, class F, class...T>
vector<O> foo(F f, T&amp;&amp;...args) {
    // ↑ forgive the double-escaped ampersands, the `amp;` shouldn't be there!
    return { std::forward<T>(f(args))... };
}

vector<int> x = foo<int>(
    [](auto x) { return x + 1; },
    1,2,3
);

Deduced template parameters F and T... have to come after non-deduced parameters.

Also works for more generalized types:

template<class O, class F, class...T>
O foo(F f, T&amp;&amp;...args) {
    return { std::forward<T>(f(args))... };
}

vector<int> x = foo<vector<int>>(
    [](auto x) { return x + 1; },
    1,2,3
);