如何获取泛型类成员函数的函数指针?

问题描述 投票:0回答:2

我需要在数组中实例化不同的对象,并根据从套接字接收的数据调用它们的execute方法。在这种情况下,我想避免使用switch和if语句。

只要我不使用模板,代码就能完美运行。一旦我使用模板,它就无法编译。

问题是:我无法弄清楚这个typedef的解决方法,因为不允许将它与模板一起使用。我在这里看过一些帖子等等,但到目前为止找不到任何有用的东西。

我正在为我遇到麻烦的课程和主要课程粘贴一个基本的测试代码。其余代码不会干扰。

class Command {
public:
   template<class T>
   typedef void (T::*Action)();  
   Command( T* object, Action method ) {
      m_object = object;
      m_method = method;
   }
   void execute() {
      (m_object->*m_method)();
   }
private:
   T* m_object;
   Action m_method;
};


int main( void ) {
   Queue<Command> que;
   Command* input[] = { new Command( new test, &test::m1),
                        new Command( new test, &test::m2),
                        new Command( new test, &test::m3)};

   for (int i=0; i < 3; i++)
      que.enque( input[i] );

   for (int i=0; i < 3; i++)
      que.deque()->execute();
   cout << '\n';
}
c++ templates typedef generic-programming
2个回答
1
投票

找到了解决方案。我在这里发布它给那些有同样问题的人。

QList是QT中的模板类。对于那些没有使用QT的人,QList应该替换为这样的东西:“typedef std :: list list; list list of objects。”

这里是:

class abstract
{
public:
   virtual void execute(int z) = 0;
};

class Test: public abstract
{
public:
    void execute(int z)    { qDebug() << "-test  " << z; }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QList<abstract*> list_of_objects;

/现在能够将不同的类对象关联到不同的索引。例如:在索引0中测试,在索引1中测试...等等/

    list_of_objects.insert(0,new Test); 
    list_of_objects.at(0)->execute(1000);

    return a.exec();
}

谢谢您的帮助。


0
投票

您不能在T中使用Command,因为它不是类型的名称(除了在typedef中)。

Command需要是一个类模板。

template<class T>
class Command {
public:
   typedef void (T::*Action)();  
   Command( T* object, Action method ) {
      m_object = object;
      m_method = method;
   }
   void execute() {
      (m_object->*m_method)();
   }
private:
   T* m_object;
   Action m_method;
};

int main( void ) {
   Queue<Command<test>> que;
   Command<test>* input[] = { new Command<test>( new test, &test::m1),
                              new Command<test>( new test, &test::m2),
                              new Command<test>( new test, &test::m3)};

   for (int i=0; i < 3; i++)
      que.enque( input[i] );

   for (int i=0; i < 3; i++)
      que.deque()->execute();
   cout << '\n';
}
© www.soinside.com 2019 - 2024. All rights reserved.