看起来我无法将非捕获 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;
}
这主要是语言定义的问题,以下内容使其更加明显:
using F2 = void(*)( int );
// this works:
constexpr F2 f2 = f1;
// this does not:
constexpr F2 f2 = []( int i ) { std::cout << i << std::endl; };
实例 http://coliru.stacked-crooked.com/a/738eb6e8dc29d6e5
这基本上意味着您的希望/期望是相当合理的,但该语言目前并未以这种方式定义 - lambda 不会产生适合作为函数指针的函数指针。constexpr
.
但是,有一个解决此问题的建议:N4487 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4487.pdf.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)