繁体   English   中英

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

[英]How do I obtain a function pointer for a generic class member function?

我需要实例化数组中的不同对象,并根据从套接字接收的数据调用它们的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';
}

发现了一个解决方案。 我将其发布在这里,供那些有相同问题的人使用。

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中测试Test2 ...,依此类推 /

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

    return a.exec();
}

谢谢您的帮助。

您不能在Command使用T ,因为它不是类型的名称( 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';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM