C++ passing method pointer as template argument

前端 未结 5 948
攒了一身酷
攒了一身酷 2021-01-19 23:44

I have a caller function like this:

template
void CallMethod(T *object){
    (object->*method)(args);
}
         


        
5条回答
  •  情话喂你
    2021-01-20 00:42

    It looks like you're trying to implement an interface via templates. It might be possible, but wouldn't it be nicer to have a base class with a virtual function, and use a base class pointer to access the virtual function via a simple function call?

    Header:

    class AbstractBase
    {
    public:
        virtual void func() = 0;
    }
    class SubClass : public AbstractBase
    {
    public:
        void func();
    }
    

    Source file:

    void SubClass::func()
    {
        std::cout << "Virtual function called.\n";
    }
    

    Example usage:

    int main()
    {
        AbstractBase* base;
        base = new SubClass();
        base->func(); // virtual function call through base pointer will use SubClass's implementation
        return 0;
    }
    

    You can store a vector of pointers (or smart pointers if you use boost or C++0x) which you can loop through and use this to do all kinds of SubClass dependent stuff.

    Alternatively, use boost::function or std::function (C++0x) which is an object containing the member function in question and pass that as a template parameter, using the object instance as a first argument. Which comes down to a workaround of the above.

    UPDATE: Seeing that you need a plain C function pointer, there are some tricks that might imapct runtime performance in c++0x or boost: bind, function::target and so forth...

    You will need this to get a function pointer out of a std/boost::function, and this to bind the first argument to an object. bind acts at runtime, so maybe a template would be better in this case...

提交回复
热议问题