计时定时器 class 来自 class 的传递方法无效

Chrono timer class pass method from class not function

我正在尝试使用 tutorialspoint 中的代码,但是当我想将函数放入 class 时遇到问题。

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later {
   public:
      template <class callable, class... arguments>
      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();
      }
   }
};
void test1(void) {
   return;
}

int main() {
   later later_test1(3000, false, &test1);
   later later_test2(1000, false, &test2, 75);
   later later_test3(3000, false, &test2, 101);
}

我想把函数test1放在同一个class或定义一个新的one.The问题是代码无法编译。

 #include <functional>
    #include <chrono>
    #include <future>
    #include <cstdio>
    class later {
       public:
          template <class callable, class... arguments>
          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();
          }
       }

    void test1(void) {
       return;
    }
    };
int main() {
   later later_test1(3000, false, &later::test1);
   later later_test2(1000, false, &test2, 75);
   later later_test3(3000, false, &test2, 101);
}    

在您的第二段代码中,test1 是 later 的 non-static 成员函数。这意味着它需要一个对象才能被调用。

静态化:

    static void test1(void) {
       return;
    }