假设我在 C++20 中有以下代码,使用 P0428 中引入的显式模板参数 lambda 功能:
auto f = []<auto val>(int a) { printf("%d", val + a); };
我需要将 lambda f
的函数指针转换为带有显式专用值的 void(*)(int)
(我需要一个显式的 C ABI 链接) ,成员函数调用将导致不同的参数传递寄存器),考虑到以下代码是非法的:
using intfn = void(*)(int);
f.template operator intfn<400>(); // illegal
f.template operator()<400>(0); // legal, but not what I need: is a member function call
(查看Is it possible to call templated user-defined conversion operator with explicit template arguments?的答案)
...在当前的 C++ 语言中是否有其他方法来获取函数指针,例如通过使用某种隐式转换?
最佳答案
您可以利用非捕获 lambda 在 c++20 中可默认构造的事实。
#include <iostream>
#include <tuple>
template <typename F>
struct args_tuple_maker;
template <auto P, typename F, typename... Args>
auto make_function_pointer(F, std::tuple<Args...>) {
return +[](Args... args){ F{}.template operator()<P>(std::forward<Args>(args)...); };
}
int main() {
auto f = []<auto val>(int a) { printf("%d", val + a); };
auto f_ptr = make_function_pointer<200>(f, std::tuple<int>{});
static_assert(std::is_same_v<decltype(f_ptr), void(*)(int)>, "");
f_ptr(5);
}
这不是一个完美的解决方案,但也许是您现在所能达到的最接近的解决方案。可能可以改进以从 lambda 类型推断参数。
关于C++20 'familiar template' lambda : specifying an explicit argument in function pointer conversion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64497320/