将lambda作为模板参数传递给模板化的函数指针函数 [英] Passing lambda as template parameter to templated by function-pointer function
本文介绍了将lambda作为模板参数传递给模板化的函数指针函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来我不能将一个不捕获的lambda作为模板参数传递给一个模板化的函数指针函数。我是以错误的方式做,还是不可能?
Looks like I cannot pass a no-capture lambda as a template parameter to a templated by function-pointer function. Am I doing it the wrong way, or is it impossible?
#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;
}
推荐答案
语言的定义,以下使它更明显:
It's mostly a problem in the language's definition, the following makes it more obvious:
using F2 = void(*)( int );
// this works:
constexpr F2 f2 = f1;
// this does not:
constexpr F2 f2 = []( int i ) { std::cout << i << std::endl; };
这基本上意味着您的希望/期望是相当合理的,但目前语言没有定义 - lambda不会产生适合作为 constexpr
的函数指针。
This basically means that your hope/expectation is quite reasonable, but the language is currently not defined that way - a lambda does not yield a function pointer which is suitable as a constexpr
.
但是,修正此问题的提案: N4487 。
There is, however, a proposal to fix this issue: N4487.
这篇关于将lambda作为模板参数传递给模板化的函数指针函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文