将lambda作为模板参数传递给由函数指针函数模板化

use*_*436 10 lambda templates c++11 c++14 c++17

看起来我无法将无捕获的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;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*rey 11

这主要是语言定义中的一个问题,以下内容使其更加明显:

using F2 = void(*)( int );

// this works:
constexpr F2 f2 = f1;

// this does not:
constexpr F2 f2 = []( int i ) { std::cout << i << std::endl; };
Run Code Online (Sandbox Code Playgroud)

实例

这基本上意味着你的希望/期望是非常合理的,但语言目前没有这样定义 - lambda不会产生一个适合作为a的函数指针constexpr.

但是,有一个提议要解决这个问题:N4487.