std::result_of/std::invoke_result用法总结

目录

1. 简介

2. std::result_of

3. std::result_of_t

4. std::invoke_result/std::invoke_result_t

5. 总结


1. 简介

       在C++中,有时我们需要获取函数或可调用对象的返回值类型,以便进行后续的操作,在泛型编程中很常用,特别是当不同的参数集的结果类型不同时。在早期的C++版本中,我们需要手动推导函数返回值类型,这个过程非常复杂,也容易出错。为了解决这个问题,C++11引入了std::result_of、C++14引入了std::result_of_t(),这两个模板可以方便地获取函数或可调用对象的返回值类型。而在C++17中,废弃了std::result_of而引入了更好用的std::invoke_result和std::invoke_result_t。 

2. std::result_of

       std::result_of是一个函数类型萃取器(function type traits),它可以推导函数类型的返回值类型,它定义在头文件<type_traits>中。std::result_of模板类需要两个模板参数:第一个是函数类型,第二个是函数的参数类型。它的定义如下:

template <typename F, typename... Args>
class result_of<F(Args...)>;

在模板参数中,F必须是可调用类型、对函数的引用或对可调用类型的引用Args代表函数参数类型,成员type返回可调用对象的类型.(主要用该成员来获得结果)。例如,如果我们有一个函数add,它的类型为int(int, double),我们可以按照下列示例代码来使用std::result_of以获取其返回值类型:

#include <type_traits>

int add(int x, double y)
{
    return x + static_cast<int>(y);
}

int main()
{
    std::result_of<int(int, double)>::type result = 0;
    static_assert(std::is_same<decltype(result), int>::value, "result type should be int");
    return 0;
}

在这个示例中,我们使用std::result_of<int(int, double)>::type来获取返回值类型,并使用std::is_same来检查返回值类型是否为int。这里,因为我们知道函数的入口(或理解为函数指针),所以std::result_of<int(int, double)>::type也可以改成std::result_of<decltype(add)>::type。而代码中的result是一个变量,而不是类型,所以不能直接在std::is_same中引用,即不能写成std::is_same<result, int>,必须使用decltype获取result的类型。

一个简单的实例:

#include <iostream>
#include <type_traits>
 
int fn(int) {return int();}                            // function
typedef int(&fn_ref)(int);                             // function reference
typedef int(*fn_ptr)(int);                             // function pointer
struct fn_class { int operator()(int i){return i;} };  // function-like class
 
int main() {
  typedef std::result_of<decltype(fn)&(int)>::type A;  // int
  typedef std::result_of<fn_ref(int)>::type B;         // int
  typedef std::result_of<fn_ptr(int)>::type C;         // int
  typedef std::result_of<fn_class(int)>::type D;       // int
 
  std::cout << std::boolalpha;
  std::cout << "typedefs of int:" << std::endl;
 
  std::cout << "A: " << std::is_same<int,A>::value << std::endl;
  std::cout << "B: " << std::is_same<int,B>::value << std::endl;
  std::cout << "C: " << std::is_same<int,C>::value << std::endl;
  std::cout << "D: " << std::is_same<int,D>::value << std::endl;
 
  return 0;
}

输出结果:

typedefs of int:
A: true
B: true
C: true
D: true

一个模板中应用的实例:

有一个vector<Person>,Person就是一个简单的结构体,包含name,age,city三个字段,想要编写一个Group_by函数,实现对这个vector<Person>按Person的某个字段分组.因为字段未定,编写一个模板比较好.思路是向Group_by传一个函数,让用户决定这个字段.分组比较简单,数据插入一个multimap<T,Person>返回即可,但是定义multimap中的T类型由用户传入的函数决定.于是这时候就可以用result_of来确定函数的返回值,即T的类型.

#include<iostream>
#include<map>
#include<string>
#include<vector>
#include<algorithm>
#include <utility>
using namespace std;
 
struct Person
{
    string name;
    int age;
    string city;    
};
 
vector<Person> vt ={
    {"aa",20,"shanghai"},
    {"bb",25,"beijing"},
    {"cc",20,"nanjing"},
    {"dd",25,"nanjing"}
};
 
//Group_by函数
template<typename Fn>
multimap<typename result_of<Fn(Person)>::type, Person> GroupBy(const vector<Person>& vt,const Fn& keySelect)
{
	typedef typename result_of<Fn(Person)>::type key_type;
	multimap<key_type,Person> map;
        for_each(vt.begin(),vt.end(),
                    [&](const Person& p){
                    map.insert(make_pair(keySelect(p),p));
                    });
    return map;
}
 
int main()
{   
    //按年龄分组
    auto res = GroupBy(vt, [](const Person& p){ return p.age; });
    //按城市分组
    auto res1 = GroupBy(vt, [](const Person& p) { return p.city; });
 
    //打印结果
    cout << "----------group by age:---------------" << endl;
    for_each(res.begin(),res.end(),[](decltype(res)::value_type & p){
                    cout << p.second.name <<" " << p.second.city << "  " << p.second.age  << endl;
                    });
    cout << "----------group by city:---------------"<< endl;
    for_each(res1.begin(),res1.end(),[](decltype(res1)::value_type & p){
                    cout << p.second.name <<" " << p.second.city << "  " << p.second.age  << endl;
                    });
    return 0;
}

运行结果:

3. std::result_of_t

        C++14引入了一个方便的类型别名std::result_of_t,它可以替代std::result_of<F(Args...)>::type,简化代码。使用std::result_of_t,上面的示例可以写成:

#include <type_traits>

int add(int x, double y)
{
    return x + static_cast<int>(y);
}

int main()
{
    std::result_of_t<decltype(add)> result = 0;
    static_assert(std::is_same<decltype(result), int>::value, "result type should be int");
    return 0;
}

4. std::invoke_result/std::invoke_result_t

在C++17中,std::result_of已被弃用,建议使用std::invoke_result来代替。std::invoke_result可以获取函数、成员函数和可调用对象的返回值类型。与std::result_of不同的是,std::invoke_result支持成员函数指针和指向成员函数的指针,以及可调用对象的包装器std::function。

std::invoke_result/std::invoke_result_t的定义如下:

template <typename F, typename... Args>
struct invoke_result;

template <typename F, typename... Args>
using invoke_result_t = typename invoke_result<F, Args...>::type;

在模板参数中,F代表函数类型成员函数指针类型可调用对象类型Args代表函数或成员函数的参数类型。例如,如果我们有一个函数add,它的类型为int(int, double),我们可以参照如下示例代码使用std::invoke_result_t来获取它的返回值类型:

#include <type_traits>

int add(int x, double y)
{
    return x + static_cast<int>(y);
}

int main()
{
    std::invoke_result_t<decltype(add), int, double> result = 0;
    static_assert(std::is_same<decltype(result), int>::value, "result type should be int");
    return 0;
}

在这个示例中,我们使用std::invoke_result_t<decltype(add), int, double>来获取函数add的返回值类型,并使用std::is_same来检查返回值类型是否为int。如果我们有一个类A和一个成员函数A::add(),则可以使用下列代码获取成员函数的返回值:

#include <type_traits>

class A
{
public:
    int add(int x, double y)
    {
        return x + static_cast<int>(y);
    }
};

int main()
{
    std::invoke_result_t<decltype(&A::add), A*, int, double> result = 0;
    static_assert(std::is_same<decltype(result), int>::value, "result type should be int");
    return 0;
}

在这个示例中,我们使用std::invoke_result_t<decltype(&A::add), A*, int, double>来获取成员函数A::add的返回值类型。需要注意的是,由于成员函数A::add()是属于类的,而成员函数必须通过类的对象或指针进行调用,因此需要将函数的第一个参数类型指定为该函数所在类的类型的指针类型,即"A*"。(编译器为我们隐藏了调用成员函数时所需要的this指针参数,所以这里会显得有点绕)。剩下类型就是该成员函数的其他参数类型。

如果我们有一个可调用对象,我们可以直接将它传递给std::invoke_result_t。例如:

#include <type_traits>
#include <functional>

int main()
{
    std::function<int(int, double)> add = [](int x, double y) {
        return x + static_cast<int>(y);
    };
    std::invoke_result_t<decltype(add), int, double> result = 0;
    static_assert(std::is_same<decltype(result), int>::value, "result type should be int");
    return 0;
}

我们直接将可调用对象add传递给std::invoke_result即可。需要注意的是,如果函数、成员函数或可调用对象不接受指定的参数类型,则编译时将会出现错误。

5. 总结

        综上所述,std::result_of和std::invoke_result是两个非常有用的工具,可以方便地获取函数、成员函数和可调用对象的返回值类型。它们可以避免手动推导函数返回值类型的复杂过程,减少错误和代码量。如果你需要获取函数、成员函数或可调用对象的返回值类型,建议使用std::result_of_t或std::invoke_result_t来实现。


原文链接:https://blog.csdn.net/o0onlylove0o/article/details/130276323、

https://blog.csdn.net/qq_31175231/article/details/77165279

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
In file included from /home/yhdr/2-test-2023-06_v3/sent.h:24:0, from /home/yhdr/2-test-2023-06_v3/sent.cpp:1: /usr/include/c++/7/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (*)(double*, double&, double&, double&, double&, double&), double**, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double> > >’: /usr/include/c++/7/thread:127:22: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(double*, double&, double&, double&, double&, double&); _Args = {double**, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>}]’ /home/yhdr/2-test-2023-06_v3/sent.cpp:18:153: required from here /usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (*)(double*, double&, double&, double&, double&, double&), double**, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double> > >::_M_invoke(std::thread::_Invoker<std::tuple<void (*)(double*, double&, double&, double&, double&, double&), double**, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double> > >::_Indices)’ operator()() ^~~~~~~~ /usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int ..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind ...>) [with long unsigned int ..._Ind = {_Ind ...}; _Tuple = std::tuple<void (*)(double*, double&, double&, double&, double&, double&), double**, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double>, std::reference_wrapper<double> >] _M_invoke(_Index_tuple<_Ind...>)
06-07

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值