[英]C++20 'familiar template' lambdas: specifying an explicit argument in function pointer conversion
Assuming I have the following code in C++20, using the explicit template argument lambda functionality introduced in P0428:假设我在 C++20 中有以下代码,使用 P0428 中引入的显式模板参数 lambda 功能:
auto f = []<auto val>(int a) { printf("%d", val + a); };
and I need a function pointer conversion for the lambda f
to void(*)(int)
with an explicitly specialized value (I need an explicit C ABI linkage there, member function calls will lead to different argument passing registers), given the fact that the following code is illegal:并且我需要将 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
(seeing the answer to Is it possible to call templated user-defined conversion operator with explicit template arguments? ) (查看是否可以使用显式模板参数调用模板化用户定义转换运算符? )
... is there any other way to get a function pointer in the current C++ language, eg by using some sort of implicit conversion? ...有没有其他方法可以在当前的 C++ 语言中获取函数指针,例如通过使用某种隐式转换?
You can leverage the fact that a non-capturing lambda is default-constructible in c++20.您可以利用一个事实,即非捕获 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);
}
It's not a perfect solution, but maybe as close as you can get right now.这不是一个完美的解决方案,但也许是你现在所能得到的。 Could probably be improved to deduce the arguments from the lambda type.可能可以改进以从 lambda 类型推断参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.