簡體   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