繁体   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