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

时间:2019-02-23 06:58:07

标签: c++ templates typedef generic-programming

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

2 个答案:

答案 0 :(得分: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中进行Test2 ...,依此类推 /

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

    return a.exec();
}

感谢您的帮助。

答案 1 :(得分:0)

namespace std内不能使用std,因为它不是类型的名称(using std::cout;中除外)。

T必须是一个类模板。

Command
相关问题