Passing lambda as template parameter to templated by function-pointer function

早过忘川 提交于 2019-12-05 02:42:27

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; };

Live example

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.

There is, however, a proposal to fix this issue: N4487.

This is not viable because f2 is not constexpr (i.e., is a runtime variable). As such it cannot be used as a template parameter. You could alter your code and make it more generic in the following manner:

#include <iostream>

template<typename F, typename ...Args>
void fun(F f, Args... args) {
  f(args...);
}

void f1( int i ) {
    std::cout << i << std::endl;
}

int main() {
    auto f2 = []( int i ) { std::cout << i << std::endl; };
    fun(f1, 42);
    f2( 42 );
    fun(f2, 42 );
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!