C++ 函数对象(Function Object)是什么?C++重载小括号()是什么作用?

在了解重载()之前,首先要理解C++里面的函数对象的概念。

1. 什么是函数对象?

A FunctionObject type is the type of an object that can be used on the left of the function call operator.

即:函数对象类型是可以在函数调用操作符(PS:就是小括号())左侧使用的对象类型
根据文档可以总结出函数对象的几种类型:

  1. 函数或者函数引用(需要隐式转换)
  2. 函数指针
  3. < functional >头文件中定义的所有函数对象(如less,greater)
  4. < functional >头文件中一些函数的返回值

Notes
Functions and references to functions are not function object
types, but can be used where function object types are expected due to
function-to-pointer implicit conversion.

Standard library
All pointers to functions satisfy this requirement.
All function objects defined in < functional >
Some return types of functions of < functional >

此外还有:
5. lambda表达式(C++11之后)
6. 重载了函数调用运算符()的类的对象

在C++中,自定义的比较函数中:常见的传入函数名,less或者greater对象都属于这种函数对象。但是,类似下面这种是做了隐式类型转换的。(具体转换流程没去看,有清楚的可以留言哈)

// 传入函数名
vector<int> vec;
bool cmp(const pair<int, int>& A. const pair<int, int>& B) {
	return A.second < B.second;
}
sort(vec.begin(), vec.end(), cmp);

下面是其他对于函数对象的几种用法的实例(函数指针,重载了函数调用运算符()的类的对象
,lambda表达式)

#include <iostream>
 
void foo(int x) { std::cout << "foo(" << x << ")\n"; }
 
int main()
{
    void(*fp)(int) = foo;
    fp(1); // calls foo using the pointer to function
 
    struct S {
        void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
    } s;
    s(2); // calls s.operator()
    s.operator()(3); // the same
 
    auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
    lam(4); // calls the lambda
    lam.operator()(5); // the same
}

2. 重载函数调用运算符()小括号

小括号是函数调用运算符。
重载()小括号,也就是重载函数调用运算符。

当用户定义类重载函数调用operator()时,它将成为FunctionObject类型。而FunctionObject类型可以当作一个函数一样来调用,这种类型的对象可以在函数调用表达式中使用:

这样说可能较为晦涩,但是下面的实例应该很好看懂:

// An object of this type represents a linear function of one variable a * x + b.
struct Linear
{
    double a, b;
 
    double operator()(double x) const
    {
        return a * x + b;
    }
};
 
int main()
{
    Linear f{2, 1};  // Represents function 2x + 1.
    Linear g{-1, 0}; // Represents function -x.
    // f and g are objects that can be used like a function.
 
    double f_0 = f(0);
    double f_1 = f(1);
 
    double g_0 = g(0);
}

重载函数调用运算符()之后的类就是函数对象(FunctionObject)类,就有了函数对象(FunctionObject)类的功能,其实例化的对象,就是本文第一节所介绍的。

参考资料:

  1. https://en.cppreference.com/w/cpp/named_req/FunctionObject
  2. https://en.cppreference.com/w/cpp/language/operators
    第二个链接参看其中的Function call operator这一节,这两个文档写的非常好,强烈推荐
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值