C++20 'familiar template' lambda : specifying an explicit argument in function pointer conversion

标签 c++ c++20

假设我在 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/

相关文章:

可以将整数、 float 、 double 或任何其他可转换为 float 的 C++ 函数

c++ - 在编译时将 const char* 转换为 const char_type*

c++ - 明确的概念特化

c++ - std::allocator 怎么这么快?

c++ - 概念-如何限制积分模板值

c++ - 不能在 C++20 (Visual Studio) 中使用 iostream 作为模块

c++ - P1008 ("prohibit aggregates with user-declared constructors") 在实践中何时有用?

c++ - C++ 中的基本 if 语句 3 值

c++ - 具有调用者上下文的模板函数?

c++ - 如何正确使用BOOST_THROW_EXCEPTION?