Local Types With Virtual Functions

Local types defined in functions can have virtual functions. This opens up many possibilities for convenient patterns that require a small amount of local code to be given to some other entity.

The simplest form of this is perhaps a (non-copyable) functor type with a virtual operator () () function:


    class local_functor {
    public:
        virtual void operator () () = 0;
    };
    
    void user( local_functor& func ) {
        func();
    }
    
    void provider()
    {
        // no need to name this type
        struct : local_functor {
            void operator () () {
                // ...
            }
        } func;
        
        user( func );
    }

The non-copyability can be worked around with a helper class.


    class local_functor {
    public:
        virtual void operator () () = 0;
    };
    
    class local_functor_ref {
        local_functor* func;
    public:
        local_functor_ref() : func( 0 ) { }
        
        local_functor_ref( local_functor& f ) : func( &f ) { }
        
        operator () () {
            (*func)();
        }
    };
    
    void user( local_functor_ref func ) {
        func();
    }
    
    void provider()
    {
        // no need to name this type
        struct : local_functor {
            void operator () () {
                // ...
            }
        } func;
        
        user( func );
    }

This has many possibilities. It can be used to work around some of the limitations caused by the fact that templates cannot take as parameters local types. :-)


Blargg's C++ Notes