简体   繁体   English

如何创建将保存指向函数的指针的队列?

[英]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.通过使用普通的myMathElement->Print_1你不提供任何对象,只是一个指向成员函数的指针。

Either usestd::bind to provide the object as the first argument to the function:要么使用std::bind提供对象作为函数的第一个参数:

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

Or use lambda expressions :或者使用lambda 表达式

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.至于你的错误,要么你是因为Queue类中的一些问题(你没有向我们展示)而得到它们,但更有可能错误不是来自push调用,而是来自对func成员的分配。

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 .如上图所示的std::bind调用,您必须使用&MyMath::Print_1

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

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