【问题标题】:Schedule event later in C++: how to pass the task to be ran稍后在 C++ 中安排事件:如何传递要运行的任务
【发布时间】:2020-07-15 16:33:19
【问题描述】:

我正在尝试运行以下代码来安排 A 类中的 taskFun 在 1000 毫秒后开始运行。当我运行这段代码时,我得到了这个错误:

main.cpp:9:70: error: no type named 'type' in 'std::__1::result_of<void (A::*(int))(int)>'
    std::function<typename std::result_of < callable(arguments...)>::type() > task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
main.cpp:29:10: note: in instantiation of function template specialization 'later<void (A::*)(int), int>' requested here
         later(1000, true, &A::taskFun, 101);
     ^

如果我将 taskFun 定义为静态函数,我不会收到此错误。但我不希望它是静态的。有没有办法更新“稍后”功能以接受非静态输入?

    #include <functional>
    #include <chrono>
    #include <future>
    #include <cstdio>
    #include <iostream>
    
    template <class callable, class... arguments>
    void later(int after, bool async, callable f, arguments&&... args) {
        std::function<typename std::result_of < callable(arguments...)>::type() > task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
    
        if (async) {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        } else {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }
    


    class A {
    public:
    
        A() {
        }
    
        void callLater() {
            later(1000, true, &A::taskFun, 99);
        }
    
        void taskFun(int a) {
            std::cout << a << "\n";
        }
    
    };

【问题讨论】:

    标签: c++ visual-c++ c++17


    【解决方案1】:

    你很亲密。

    作为一个非静态成员函数,taskFun 有一个隐藏参数,它变成了this。除了参数99,您还需要将此绑定到回调:

    later(1000, true, &A::taskFun, this, 99);
    

    现在参数列表匹配。

    不过,lambda 可能会更好:

    later(1000, true, [=]() { taskFun(99); });
    

    如果您坚持这种方法,您可以摆脱std::function 来自laterarguments 参数包。

    【讨论】:

    • 感谢您的有用回复。能否请您告诉我如何更新源代码以使用 lambda?
    • @MohammedZiad 答案中有一个例子。
    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 2016-03-05
    • 2010-12-08
    相关资源
    最近更新 更多