Function pointer to template class member functions

前端 未结 2 1584
孤城傲影
孤城傲影 2021-01-20 05:24

I have a templated class defined (in part) as

template  MyClass
{
public:
   void DoSomething(){}
};

If I want to call DoSom

相关标签:
2条回答
  • 2021-01-20 05:56

    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!

    0 讨论(0)
  • 2021-01-20 05:59

    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>);
    
    0 讨论(0)
提交回复
热议问题