News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ tips - Menu item callbacks with templates

Started by ben2ong2, October 07, 2006, 04:04:43 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

RESPONSE: Scott Meyers, You are not allowed to view links. Register or Login, 30 Apr 93

    class BaseMenuItem {
    public:
        virtual void invoke() const = 0;
    };

    template<class Class, class MemFuncPtr, class Param>
    class MenuItem: public BaseMenuItem {
    private:
        Class&      object;
        MemFuncPtr  function;
        Param&      parameter;

    public:
        MenuItem(Class& obj, MemFuncPtr mfp, Param& p):
          object(obj), function(mfp), parameter(p) {}

        virtual void invoke() const { object.*mf(p); }
    };

Now you can create a MenuItem object for any class, member function, and
parameter you like, with the proviso that the member function must have
exactly one formal parameter.

It seems to me like this should work, but as I said, I haven't tried it
yet.  Comments?



RESPONSE: Stephen G. Edwards <edwards@kong.gsfc.nasa.gov>

Yes, it does work.  You've also just inadvertently solved a big problem I was
having trying to use this technique to implement a callback mechnism for
Motif.  I constrained my template a bit more like this:

    template<class Class>
    class MenuItem: public BaseMenuItem {
    private:
        Class&      object;
        void (Class::*function)(FixedType p);
        FixedType&      parameter;

    public:
        MenuItem(Class& obj, void (Class::*mfp)(FixedType), FixedType& p):
          object(obj), function(mfp), parameter(p) {}

        virtual void invoke() const { object.*mf(p); }
    };

The compiler choked when instantiating the MenuItem constructor.  I learned
there is a bug in cfront 3.0.1 that causes it to incorrectly reject the mfp
argument.  This should do the job, though.  Thanks! :) :) :)
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login