更新时间:2023-11-10 07:51:33
Use a variadic template with perfect forwarding of its parameters, eg:
#include <iostream>
#include <thread>
#define __PRETTY_FUNCTION__ __FUNCSIG__
template<class Function, class... Args>
void runFunctionInThread(Function f, Args&&... args) {
std::thread t(f, std::forward<Args>(args)...);
t.detach();
}
void isolatedFunc1() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
void isolatedFunc2(int value) { std::cout << __PRETTY_FUNCTION__ << " value is " << value << "\n"; }
void isolatedFunc3(int value1, int value2) { std::cout << __PRETTY_FUNCTION__ << " value1+value2 is " << value1 + value2 << "\n"; }
int main()
{
runFunctionInThread(&isolatedFunc1);
runFunctionInThread(&isolatedFunc2, 2);
runFunctionInThread(&isolatedFunc3, 3, 3);
}
但是,这是相当多余的,因为 std :: thread
可以直接为您处理此操作,因此您根本不需要 runFunctionInThread()
,例如:
However, this is fairly redundant since std::thread
can handle this directly for you, so you don't need runFunctionInThread()
at all, eg:
int main()
{
std::thread(&isolatedFunc1).detach();
std::thread(&isolatedFunc2, 2).detach();
std::thread(&isolatedFunc3, 3, 3).detach();
}