Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2003-08-01 17:29:07


David Abrahams wrote:
> Here's an example I just cooked up of using the PP lib to solve a
> classic C++ OO problem: repeated boilerplate in the definition of
> Pimpl classes.

There is another variation of the idiom, sometimes called "hidden state",
which doesn't have the shortcoming in the first place:

    class foo
    {
     public:
        foo();
        foo(int);

        int f() const;
        void g(double*);

     private:
        struct state;
        scoped_ptr<state> m_state;
    };

and then in the .cpp file:

    struct foo::state
    {
        // c'tor only!
        state( int b, double* fu );

        int bar;
        double* fu;
    };

    foo::foo( int b )
        : m_state( new state( b, 0 ) )
    {
    }

    int foo::f() const
    {
        return m_state->bar;
    }

    void foo::g( double* ptr )
    {
        m_state->fu = ptr;
    }

A nice by-product property of the technique is that now you don't have to
prefix/postfix the state's member names since their are always accessed
throuh 'm_state->' (or 'state().' or 'self().' or whatever accessor you
prefer).

Here at work we have a little helper class that hides the rest of the
boilerplate stuff:

    class foo
        : hidden_state<foo>
    {
     public:
        foo();
        foo(int);

        int f() const;
        void g(double*);
    };

FWIW :),
Aleksey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk