模板和函数指针

Template and function pointer

本文关键字:指针 函数      更新时间:2023-10-16

是否可以从模板中存储类,而不将整个类作为模板?

任务:

我有两个函数,v1没有参数,v2有参数,如果v1在某个地方被调用,则Use[(]不会发生任何变化,如果v2在某个位置被调用,Use[()]应该使用我从DoSometh(T*)获得的实例执行一个函数_ptr。

例如

    class MyClass
    {
      //v1 no parameters
      void DoSomething()
      {
      }
      //v2 with parameter
      template<class T>
      void DoSomething(T* instance, void (T::*func)())
      {
        store somewhere?? = instance;
      }
      void Use()
      {
        //if DoSometh(T* instance) was used before
        if(instance != NULL)
        {
            (*instance->)//call function pointer from DoSomething(T*,void  (T::*)())
        }
      }
    }
std::function problem
update:

class Timer : public ITickable
{
  std::function<void()> test; //adding this does weird things
  virtual void Tick() {}
}
class MyClass
{
   ITickable* tickable_; 
void Tick()
{
    tickable_->Tick(); //let's assume it points to a Timer obj.
}

}

我认为std::functionstd::bind(C++11)确实实现了您想要的,正如评论中所建议的那样。Timer类的简化模型可以是:

class Timer
{
    std::function<void()> m_task;
public:
    template <typename T>
    void setTask(T &instance, void (T::*fcn)()) // consider T const & if applicable
    {
        m_task = std::bind(fcn, &instance);
    }
    void fire()
    {
        if (m_task) // std::function overloads operator bool()                                                                          
            m_task();
    }
};

当用一个对象和一个可以在该对象上调用的成员函数调用setTask时,就会创建一个std::function对象(当然,您可以选择在构造函数中执行此操作)。当计时器触发时,会检查此对象(使用std::function提供的operator bool()),如果它是可调用的(例如,当setTask()以前被调用时),它会调用函数。

例如:

class MyClass
{
public:
    void func()
    {
        std::cout << "Hi from MyClassn";
    }
};
class MyOtherClass
{
public:
    void func()
    {
        std::cout << "Hi from MyOtherClassn";
    }
};

int main(int argc, char **argv)
{
    MyClass x1;
    MyOtherClass x2;
    Timer t1, t2;
    t1.setTask(x1, &MyClass::func);
    t2.setTask(x2, &MyOtherClass::func);
    t1.fire();
    t2.fire();
}