Function call operator [duplicate]

☆樱花仙子☆ 提交于 2019-12-01 05:12:08

That operator turns your object into functor. Here is nice example of how it is done.

Next example demonstrates how to implement a class to use it as a functor :

#include <iostream>

struct Multiply
{
    double operator()( const double v1, const double v2 ) const
    {
        return v1 * v2;
    }
};

int main ()
{
    const double v1 = 3.3;
    const double v2 = 2.0;

    Multiply m;

    std::cout << v1 << " * " << v2 << " = "
              << m( v1, v2 )
              << std::endl;
}

It makes the object "callable" like a function. Unlike a function though, an object can hold state. Actually a function can do this in a weak sense, using a static local, but then that static local is permanently there for any call to that function made in any context by any thread.

With an object acting as a function, the state is a member of that object only and you can have other objects of the same class that have their own set of member variables.

The entirety of boost::bind (which was based on the old STL binders) is based on this concept.

The function has a fixed signature but often you need more parameters than are actually passed in the signature to perform the action.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!