问题描述
我正在尝试从tutorialspoint使用代码,但是当我要将函数放在类中时遇到了问题。
#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,&test2,75);
later later_test3(3000,101);
}
我想将函数test1放在同一个类中,还是要定义一个新的类。问题是代码无法编译。
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later {
public:
template <class callable,class... arguments>
later(int after,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,&later::test1);
later later_test2(1000,101);
}
解决方法
在第二段代码中,test1
是后面的非静态成员函数。这意味着它需要一个对象才能被调用。
将其设为静态:
static void test1(void) {
return;
}