C++17新特性 invoke_result_t 的使用

invoke_result_t 是 C 编程中的一种类型,用于表示通过函数指针调用的函数的结果。通常用于存储函数的返回值和在函数执行过程中可能生成的错误代码。

要使用 invoke_result_t,您需要在代码中包含适当的头文件。这通常是 <invoke.h> 或
< functional>,具体取决于您的平台和编译器。

一旦包含了必要的头文件,就可以像使用任何其他数据类型一样使用 invoke_result_t。例如,您可以定义一个类型为 invoke_result_t 的变量来保存函数调用的结果,或者将其用作使用函数指针调用其他函数的函数的返回类型。

以下是使用 invoke_result_t 定义一个接受函数指针作为参数并返回函数调用结果的函数的示例

#include <functional>
#include <iostream>

// Define a function that takes a function pointer and arguments for the function
template <typename Func, typename... Args>
std::invoke_result_t<Func, Args...> invoke(Func func, Args... args)
{
    // Invoke the function and return the result
    return std::invoke(func, args...);
}


// Define a function that takes an int and returns a double
double foo(int x)
{
    return x * 2.5;
}

int main()
{
    // Invoke the foo function and store the result in a variable
    auto result = std::invoke(foo, 10);

    // Print the result
    std::cout << result << std::endl;

    return 0;
}
输出结果:
25
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值