簡體   English   中英

如何創建將保存指向函數的指針的隊列?

[英]how to create queue that will hold pointer to function?

我嘗試制作可以接收指向函數的指針的隊列 - 但我找不到如何去做

這是我的代碼

        struct TaskElement
    {
        int id;
        std::function<void()> func;

        void operator()()
        {
            func();
        }
    };

    int main()
    {

        MyMath* myMathElement = new MyMath();

        myMathElement->Print_1();

        Queue<TaskElement> myQueue;


        TaskElement t1;
        t1.id = 1;
        t1.func = myMathElement->Print_1;

        TaskElement t2;
        t2.id = 2;
        t2.func = &myMathElement->Print_2;


        myQueue.push(t1);     Error !!! &': illegal operation on bound member function expression
        myQueue.push(t2);     Error !!! &': illegal operation on bound member function expression

        auto rec1 = myQueue.pop();

        rec1();



        std::cin.get();
    }

非靜態成員函數需要一個被調用的對象。 通過使用普通的myMathElement->Print_1你不提供任何對象,只是一個指向成員函數的指針。

要么使用std::bind提供對象作為函數的第一個參數:

t1.func = std::bind(&MyMath::Print_1, myMathElement);

或者使用lambda 表達式

t1.func = [myMathElement]() { myMathElement->Print_1(); };

至於你的錯誤,要么你是因為Queue類中的一些問題(你沒有向我們展示)而得到它們,但更有可能錯誤不是來自push調用,而是來自對func成員的分配。

您應該從作業中獲取它們,因為它們不是有效作業。 你不能像那樣使用成員函數,你必須使用地址運算符&(或結構)而不是對象的完整范圍。 如上圖所示的std::bind調用,您必須使用&MyMath::Print_1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM