Lambda closure type and default argument in function template

The following code looks fine according to [expr.prim.lambda] :

#include<functional> typedef int(*func1)(int); typedef std::function<int(int)> func2; int function(int) { return 0; } template<typename F = func1> int function1(F f = function) { return 0; } template<typename F = func2> int function2(F f = function) { return 0; } template<typename F = func1> int function3(F f = [](int i){return 0;}) { return 0; } template<typename F = func2> int function4(F f = [](int i){return 0;}) { return 0; } 

However, gcc (4.8.1) complains about function3 and function4 and shows an error

default argument for template parameter to include class '__lambda'

Can someone explain this error?

+4
source share
1 answer

Can I suggest a workaround?

Remove the default template argument for function3 (and function4 ):

 template<typename F> int function3(F f = [](int i){return 0;}) { return 0; } 

You can call it like this:

 function3<func1>(); 

but I think you want you to be able to do this:

 function3(); 

Is not it? Then create another overload of function3 , which is a function, not a template function:

 int function3(func1 f = [](int i){return 0;}) { return function3<func1>(f); } 
+2
source

Source: https://habr.com/ru/post/1496368/


All Articles