Rules around forward template functions to template functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//g++  5.4.0

#include <iostream>
#include <algorithm>

template<typename T>
void func(const T& func)
{
    std::cout << func(1, 2);
}


int main()
{
    func([](auto&&... whatever){ return 
    std::min(std::forward<decltype(whatever)>(whatever)...); });
}


The above works. But if I used std::min directly as an argument to func, then it's not allowed. I get that part (that it's not allowed). But what makes generic lambdas special? Also is there a good way to reuse the...

1
2
[](auto&&... whatever){ return 
    std::min(std::forward<decltype(whatever)>(whatever)...); }


...pattern (for passing any STL function, not just std::min) without a macro?
Last edited on
C++ doesn't allow template arguments to depend on stuff outside the immediate context of the substitution: that is, in the signature of the candidate function.

Lambdas get around this by not depending on stuff inside the function. It's not a template, but an instance of a class which defines a member function template named ClosureType::operator().

Rather than std::min, you would usually pass an instance of std::less<void>. That's another class whose operator() deduces the types of its operands:
 
func(std::less<>{})

Also is there a good way to reuse [...] without a macro?

Not currently.
Last edited on
Awesome, thanks. Makes sense; the generic lambda is still an instance, just one that has a template operator() inside it. Is there a library equivalent for all the algorithms though? I get that min/max is std::less, but what about say std::replace?
Last edited on
Registered users can post here. Sign in or register to post.