【发布时间】:2015-09-10 23:26:43
【问题描述】:
看起来我无法将无捕获 lambda 作为模板参数传递给由函数指针函数模板化的函数。是我做错了,还是不可能?
#include <iostream>
// Function templated by function pointer
template< void(*F)(int) >
void fun( int i )
{
F(i);
}
void f1( int i )
{
std::cout << i << std::endl;
}
int main()
{
void(*f2)( int ) = []( int i ) { std::cout << i << std::endl; };
fun<f1>( 42 ); // THIS WORKS
f2( 42 ); // THIS WORKS
fun<f2>( 42 ); // THIS DOES NOT WORK (COMPILE-TIME ERROR) !!!
return 0;
}
【问题讨论】:
-
使用
std::function。 -
f2 是一个变量 - 运行时参数。模板需要构建时间参数(常量和类型)。尝试添加 const,但它可能不起作用。
标签: templates c++11 lambda c++14 c++17