为什么运营商覆盖()? [英] Why override operator()?

查看:174
本文介绍了为什么运营商覆盖()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

升压库,它们被重载()运算符的信号。

In the Boost Signals library, they are overloading the () operator.

这是C ++中的约定?对于回调,等等?

Is this a convention in C++? For callbacks, etc.?

我有一个同事(谁恰好是一个巨大的推动风扇)的code看到了这一点。所有的升压善良在那里的,这不仅导致混乱我。

I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me.

任何有识之士为这个超载的原因是什么?

Any insight as to the reason for this overload?

推荐答案

重载运算符时的一个主要目标()是创建一个仿函数。一个仿函数的行为就像一个功能,但它有它是有状态的优势,这意味着它可以保持数据反映其调用之间的状态。

One of the primary goal when overloading operator() is to create a functor. A functor acts just like a function, but it has the advantages that it is stateful, meaning it can keep data reflecting its state between calls.

下面是一个简单的仿函数的例子:

Here is a simple functor example :

struct Accumulator
{
    int counter = 0;
    int operator()(int i) { return counter += i; }
}
...
Accumulator acc;
cout << acc(10) << endl; //prints "10"
cout << acc(20) << endl; //prints "30"

仿函数与大量泛型编程使用。许多STL算法都写在一个非常普遍的方式,让你可以插入自己的函数/仿到算法。例如,算法的std :: for_each的让你一个范围中的每个元素上应用的操作。它可以实现类似的东西:

Functors are heavily used with generic programming. Many STL algorithms are written in a very general way, so that you can plug-in your own function/functor into the algorithm. For example, the algorithm std::for_each allows you to apply an operation on each element of a range. It could be implemented something like that :

template <typename InputIterator, typename Functor>
void for_each(InputIterator first, InputIterator last, Functor f)
{
    while (first != last) f(*first++);
}

您看到,因为它是由一个函数参数化这个算法是非常通用的。通过使用操作符(),这个功能可以让你使用一个仿函数或函数指针。下面是显示这两种可能性的例子:

You see that this algorithm is very generic since it is parametrized by a function. By using the operator(), this function lets you use either a functor or a function pointer. Here's an example showing both possibilities :

void print(int i) { std::cout << i << std::endl; }
...    
std::vector<int> vec;
// Fill vec

// Using a functor
Accumulator acc;
std::for_each(vec.begin(), vec.end(), acc);
// acc.counter contains the sum of all elements of the vector

// Using a function pointer
std::for_each(vec.begin(), vec.end(), print); // prints all elements


关于你对运营商的问题()超载,以及是的,它是可能的。可以完美写出具有几个括号运算符函子,只要你尊重方法重载的基本规则(例如仅在返回类型超载是不可能的)。


Concerning your question about operator() overloading, well yes it is possible. You can perfectly write a functor that has several parentheses operator, as long as you respect the basic rules of method overloading (e.g. overloading only on the return type is not possible).

这篇关于为什么运营商覆盖()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆