I am trying to create a C++ function that takes any function with any number of arguments and pass it to std::thread
to start a thread with it.
#include <iostream>
#include <thread>
#define __PRETTY_FUNCTION__ __FUNCSIG__
void runFunctionInThread(void(*f)()) { std::thread t(f); t.join(); }
void runFunctionInThread(void(*f)(int), int value) { std::thread t(f, value); t.join(); }
void runFunctionInThread(void(*f)(int, int), int value1, int value2) { std::thread t(f, value1, value2); t.join(); }
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);
}
Is there anyway to create a single runFunctionInThread
function that works for any function with any number of arguments and any type?