Function pointer to template class member functions

为君一笑 提交于 2019-12-31 01:54:11

问题


I have a templated class defined (in part) as

template <class T> MyClass
{
public:
   void DoSomething(){}
};

If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.

My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.

Has anyone any suggestions?


回答1:


Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.

Something like this:

class Base { 
public:
  virtual ~Base(){}
  virtual void DoSomething() = 0;
}

template <class T> class MyClass : public Base {
public:
    void DoSomething(){}
};

std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);



回答2:


You know, that is just what I needed to do. Bizzarly I had discounted it as a solution valid for my usecase early on, for reasons that now escape me. I think I was blinded by some metaprogramming stuff I'm doing in the same place for compile-time dispatch (i.e. confusing compile time and runtime in my addled brain).

Thanks for the jolts!



来源:https://stackoverflow.com/questions/146275/function-pointer-to-template-class-member-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!