C++ PowerTip #4: Use Functors for Local Functions

Posted: September 15, 2010 in C++, PowerTips, Programming Languages
Tags: , , ,

At some point, you find yourself writing a C++ method that ends up having a lot of repetitious code that is very context-specific to that method. Sure, you could create a private method that encapulates the repetitious code. But, that approach brings about 2 problems that I respectively call class namespace pollution (declarations at class scope level that should be done at a lower or higher scope level) and local context exposure (context declarations at class scope that are specific to only one method). Both are readability issues that can create confusion for later maintainers. Unfortunately, this leads to further degradation of the code.

A good solution that avoids these readability and maintainability problems is a local functor. Recall that a functor is a class with function-call semantics on its instances. This functor is declared, defined, instantiated and utilized completely at method scope and contains the common code called from multiple places in the method. Nice, clean and tight!

In addition to code, the functor can also carry context data in the form of data members.

Example

void SomeClass::SomeMethod()
{
    class LocalFunctor
    {
    public:
        void operator()(....)
        {
            // TODO: Common code here
        }
    };
    ....
    if (/* some condition */)
    {
        ....
        //  implicit instantiation of functor followed by call to
        // overloaded operator () with the arguments
        LocalFunctor(/* args for this case */);
        ....
        // functor instance implicitly destroyed when this
        // block exits
    }
    else if (/* some other condition */)
    {
        ....
        LocalFunctor(/* args for this different case */);
        ....
    }
    ....
}

As you can see, the functor is an ordinary class. The function-call semantics come from overloading the function call operator (). Other than that, most anything a class can do a functor can do.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s