I am currently working on on some code in which I need to use a lambda as a template parameter like in the following example:
#include <iostream>
template<void(*func)(int)>
struct FunctionCaller{
FunctionCaller() {func(5);}
};
void RealFunction(int i){
std::cout << i*2 << std::endl;
}
int main(){
FunctionCaller<[](int i){std::cout << i << std::endl;}> caller; //should print 5
FunctionCaller<RealFunction> caller2; //should print 10
return 0;
}
I tried compiling this example with recent (C++17 supporting) versions of both GCC and Clang (versions 8.2.1 and 7.0.0 respectively) to get various errors that amount to lambda expressions not being allowed in template arguments. I am using the correct compiler flags to enable C++17 support.
This, however, seems to me like it should work because the book C++ Primer 5th edition says that any constant expression can be used for non-type template arguments, and in C++17, and this Stack Overflow post tells me that a lambda is a constant expression in C++17 and later.
After extensive research, it seems like the C++17 standard explicitly forbids lambdas as a template parameter. What is the rationale behind this restriction? What blows up if it is not in place?
EDIT: This question has some relevant information, but it only says that this restriction exists to prevent lambdas from appearing in a method signature, without any information as to why that is problematic.