代码之家  ›  专栏  ›  技术社区  ›  Ant

此模式的重点是什么:使用结构体包含单个方法

  •  8
  • Ant  · 技术社区  · 16 年前

    class outerClass
    {
        struct innerStruct
        {
            wstring operator()( wstring value )
            {
                //do something
                return value;
            }
        };
    
        void doThing()
        {
            wstring initialValue;
            wstring finalValue = innerStruct()( initialValue );
        }
    };
    

    与以下内容相比,这有什么优势:

    class outerClass
    {
        wstring changeString( wstring value )
        {
            //do something
            return value;
        }
    
        void doThing()
        {
            wstring initialValue;
            wstring finalValue = changeString( initialValue );
        }
    };
    
    2 回复  |  直到 16 年前
        1
  •  17
  •   Community Mohan Dere    8 年前

    带有运算符()的结构体通常被称为functor,有效地充当“Function对象”。您可以将这些functor与许多API(尤其是STL)一起使用,比使用典型的函数指针更容易、更稳健。函数器是对象,它们可以包含状态,并在构造过程中进行参数化,以创建一个自包含的专用处理程序。

    我推测,通常情况下,outerClass中的代码想要使用这些库函数(即std::for_each),因此开发了这种模式使其变得简单。如果你从不使用functor,那么是的,这种语法毫无意义且难以阅读(可以按照你的建议进行替换)。

    编辑:你可能会喜欢 Question 317450 ,关于运算符()。

        2
  •  4
  •   Drew Dormann    16 年前

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

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

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

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

    template< typename Predicate >
    void  DoSomething( Predicate func )
    {
      func();
    }
    

    使用a 函数 将使用 函数指针 .

    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*)() );
    

    使用a 函子 将使用 特定函数类型 .

    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 );