다음 코드를 실행하여 클래스 A에서 taskFun을 1000ms 후에 실행되도록 예약하려고합니다. 이 코드를 실행하면이 오류가 발생합니다.
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";
}
};
당신은 가까웠습니다.
비 정적 멤버 함수로서 taskFun
해진다 숨겨진 인자를 갖는다 this
. 인수 외에도 이것을 콜백에 바인딩해야합니다 99
.
later(1000, true, &A::taskFun, this, 99);
이제 인수 목록이 일치합니다.
람다는 아마도 더 좋을 것입니다.
later(1000, true, [=]() { taskFun(99); });
이 접근 방식을 고수하면 제거 할 수 std::function
및arguments
에서 매개 변수 팩 later
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다