내 앱에 C ++를 사용하여 스레드 관리를위한 라이브러리를 작성 중이며 FunctionPointer
실행 함수 내에서 실행 되는 템플릿 클래스를 작성하려고 합니다. 저는 Java 개발자이며 다음과 같이 시각화하려고합니다.
class MyRunnable : public Runnable {
public:
MyRunnable(fp)
{
mFp = fp;
}
private:
FunctionPointer mFp;
// Will be called by the thread pool using a thread
void run()
{
mFp();
}
}
class ThreadManager {
public:
void execute(MyRunnable runnable) {
executeOnAThreadPool(runnable);
}
}
C ++ 구문에 능숙하지 않기 때문에 .NET Framework에 대한 FunctionPointer
인수의 가변 개수로 인수 를 사용하도록 생성자를 정의하기가 어렵 습니다 FunctionPointer
. 다음과 같은 것 :
MyRunnable(Fp fp, Args... args)
누군가 MyRunnable
위의 클래스 생성자를 정의하는 데 도움을 줄 수 있습니까 ? 감사.
확실하지 않습니다 ...하지만 당신이 뭔가를 찾고있는 것 같습니다.
class MyRunnable
{
private:
std::function<void()> mF;
public:
template <typename F, typename ... Args>
MyRunnable (F && f, Args && ... args)
: mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
{ }
void run ()
{ mF(); }
};
다음은 전체 컴파일 예제입니다.
#include <iostream>
#include <functional>
class MyRunnable
{
private:
std::function<void()> mF;
public:
template <typename F, typename ... Args>
MyRunnable (F && f, Args && ... args)
: mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
{ }
void run ()
{ mF(); }
};
void foo (int a, long b, std::string const & c)
{ std::cout << "executing foo() with " << a << ", " << b << ", " << c << '\n'; }
int main ()
{
MyRunnable mr{foo, 1, 2l, "three"};
std::cout << "before run" << '\n';
mr.run();
}
그 인쇄
before run
executing foo() with 1, 2, three
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다