Function Objects or simply Functors.

20 05 2008


A function object is an ordinary class object with operator () overloaded. The specialty of functor is that the object can also act as function calls. But the power of a functor is – it can hold state.


See a sample code snippet for implementing a functor which compares two strings – with and with out case sensitive.

class Compare
{
public:
    // Constructor.
    Compare()
        : m_CaseSensitive(true)
    {}

    // overloaded () operator.
    BOOL operator()( CString& csString1, CString& csString2)
    {
        if( m_CaseSensitive )
        {
            // Case sensitive comparison.
            return csString1 == csString2;
        }
        else
        {
            // Non Case sensitive comparison.
            return (csString1.CompareNoCase( csString2 ) == 0) ? TRUE : FALSE;
        }
    }

    // Set the comparison.
    void SetComparisonCaseSensitive( bool CaseSensitive )
    { m_CaseSensitive = CaseSensitive; }

private:
    bool m_CaseSensitive;
};

void CompareStrings()
{
    CString csString1 = _T("Hello");
    CString csString2 = _T("hello");

    // The functor.
    Compare CompareStrings;

    // Demo of case sensitive comparison.
    BOOL bCaseSensitiveComparison = CompareStrings( csString1,
                                                    csString2);

    // non Case sensitive comparison.
    CompareStrings.SetComparisonCaseSensitive( false );
    // Demo of case sensitive comparison.
    BOOL bNonCaseSensitiveComparison = CompareStrings( csString1,
                                                       csString2);
}

In the code snippet, a string comparison is implemented by using a functor. Ideally if you want the string comparison to be able to handle both case sensitive and non-case sensitive comparisons, you’ve to use some boolean values globally or should pass it as function parameters. Or else you’ve to implement two different functions to implement both of them.

Here comes the real power of a functor. Since Its a class, can hold parameters. So that you can avoid global variables, may be some function parameters etc. Try functors… its fun!


Don’t think that functors is a new feature introduced by C++. Functors exists long before the days of C++ 🙂 One of the early languages that implemented functors was SmallTalk.


Targeted Audience – Intermediate.