Search code examples
c++functormember-pointers

functors + member pointers to create signal object


I have this code:

// signal supporter parent
class signalable {};

template <class typeT = signalable>
typedef void (typeT::*trig)(std::string);

template <class typeT = signalable>
class trigger
{
    private:
        typeT* instance;
        typeT::trig fun;

    public:
        trigger(typeT* inst, typeT::trig function)
            : instance(inst), fun(function)
        {}
        void operator ()(std::string param)
        {
            (instance->*fun)(param);
        }
};

And I get lots of compile error that I bet pros know of. I'm just confused a little bit about this context.

What I want to do is clear: Pass pointer to an object, and pointer to one of it's member functions, to make a functor and pass it over in my program.

Would appreciate your helps and "corrections".

Thank you!


Solution

  • Are you trying to do something like this?

    #include <string>
    #include <iostream>
    
    // signal supporter parent
    class signalable 
    {
    public:
        void foo(std::string s) { std::cout << "hello: " << s << std::endl; }
    };
    
    
    template <class typeT = signalable>
    class trigger
    {
    
        typedef void (typeT::*trig)(std::string);
    
        private:
            typeT* instance;
            trig fun;
    
        public:
            trigger(typeT* inst, trig function)
                : instance(inst), fun(function)
            {}
            void operator ()(std::string param)
            {
                (instance->*fun)(param);
            }
    };
    
    int main()
    {
        signalable s;
        trigger<> t(&s, &signalable::foo);
        t("world");
    }
    

    As for some of the more specific errors in your code, most of them seem to relate to your typedef. C++11 allows "template typedefs", but they don't look like that. Have a look at this thread for an example of template typedefs:

    C++ template typedef