【问题标题】:how to create queue that will hold pointer to function?如何创建将保存指向函数的指针的队列?
【发布时间】:2018-12-22 15:38:18
【问题描述】:

我尝试创建可以接收函数指针的队列 - 但我不知道该怎么做

这是我的代码

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

【问题讨论】:

标签: c++ c++11 visual-c++


【解决方案1】:

非静态成员函数需要调用对象。通过使用普通的myMathElement-&gt;Print_1,你没有提供任何对象,只是一个指向成员函数的指针。

使用std::bind 提供对象作为函数的第一个参数:

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

或者使用lambda expressions:

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

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

您应该从作业中获取它们,因为它们不是有效的作业。您不能使用这样的成员函数,您必须使用地址运算符&amp; 并使用 class (或结构)而不是对象的完整范围。如上图std::bind调用,你必须使用&amp;MyMath::Print_1

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多