简体   繁体   中英

how to create queue that will hold pointer to function?

I try to make queue that can receive pointer to function - and i can't find how to do it

this is my code

        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();
    }

Non-static member functions needs an object to be called on. By using plain myMathElement->Print_1 you're not providing any object, just a pointer to a member function.

Either usestd::bind to provide the object as the first argument to the function:

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

Or use lambda expressions :

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

As for your errors, either you get them because of some problem in the Queue class (which you haven't shown us), but more likely the errors doesn't come from the push calls but rather from the assignments to the func member.

You should get them from the assignment because they are not valid assignments. You can't use member functions like that, you must use the address-of operator & and full scoping with the class (or structure) instead of an object. As shown above with the std::bind call, you must use &MyMath::Print_1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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