这种模式的重点是:使用结构来包含单个方法

Ant*_*Ant 8 c++ struct

在我们的代码中,我们有很多这种模式的情况:

class outerClass
{
    struct innerStruct
    {
        wstring operator()( wstring value )
        {
            //do something
            return value;
        }
    };

    void doThing()
    {
        wstring initialValue;
        wstring finalValue = innerStruct()( initialValue );
    }
};
Run Code Online (Sandbox Code Playgroud)

这有什么好处:

class outerClass
{
    wstring changeString( wstring value )
    {
        //do something
        return value;
    }

    void doThing()
    {
        wstring initialValue;
        wstring finalValue = changeString( initialValue );
    }
};
Run Code Online (Sandbox Code Playgroud)

Ada*_*ght 16

带有operator()的结构通常称为仿函数,有效地充当"函数对象".您可以使用这些函数与许多API,尤其是STL,比使用典型的函数指针更容易和更强大.作为对象的函子,它们可以包含状态,并在构造期间进行参数化以创建自包含的专用处理程序.

我认为通常,你在outerClass中有代码想要使用这些库函数(即std :: for_each),因此开发了这种模式使其变得微不足道.如果你从不使用仿函数,那么是的,这种语法毫无意义且难以阅读(并且可以按照你的建议进行替换).

编辑:您可能喜欢问题317450,关于operator().


Dre*_*ann 4

这是模板化谓词的优化步骤。

这并不是函子比函数更容易使用的问题。两者在 boost 和 STL 环境中的工作方式几乎相同。

它们的不同之处在于模板实例化。

想象一个需要谓词的简单模板函数

template< typename Predicate >
void  DoSomething( Predicate func )
{
  func();
}
Run Code Online (Sandbox Code Playgroud)

使用函数将使用函数指针实例化模板实例。

void changeString();

DoSomething( &changeString );

// This creates a template instantiation expecting a pointer to a function.
// The specific pointer may be evaluated at runtime.

// void DoSomething( void(func*)() );
Run Code Online (Sandbox Code Playgroud)

使用仿函数将实例化具有特定仿函数类型的模板实例。

struct changeString
{
    void operator() ();
}

DoSomething( changeString() );

// This creates a template instantiation expecting an instance of the struct.
// The exact function being called is now known at compile time.

// void DoSomething( changeString );
Run Code Online (Sandbox Code Playgroud)

有了仿函数,现在可以很好地定义特定的功能,并且传入的结构可能不会被使用,并且可以被优化掉。