I am trying to make use of the code from tutorialspoint but I am facing a problem when I want to put the function in a 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);
}
I would like to put the function test1, whether in the same class or to define a new one.The problem is that code won't compile.
#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);
}
In your second bit of code, test1
is a non-static member function of later. That means that it needs an object in order to be called.
Make it static:
static void test1(void) {
return;
}