Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of this pattern: using a struct to contain a single method

Tags:

c++

struct

In our code we have quite a few cases of this pattern:

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

    void doThing()
    {
        wstring initialValue;
        wstring finalValue = innerStruct()( initialValue );
    }
};

What's the advantage of this over:

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

    void doThing()
    {
        wstring initialValue;
        wstring finalValue = changeString( initialValue );
    }
};
like image 515
Ant Avatar asked May 28 '09 16:05

Ant


1 Answers

A struct with an operator() is often called a functor, effectively acting as a "Function object". You can use these functors with many APIs, especially the STL, more easily and robustly than you can use typical function pointers. Functors being objects, they can contain state, and be parameterised during construction to create a self contained specialised handler.

I presume that often times, you have code in outerClass that wants to use these library functions (i.e. std::for_each), and so have developed this pattern to make it trivial. If you never use functors, then yes, this syntax is pointless and hard to read (and can be replaced as you suggest).

Edit: You might like Question 317450, about operator().

like image 146
Adam Wright Avatar answered Sep 28 '22 08:09

Adam Wright