将具有任意数量参数的任意函数传递给另一个函数

Passing any function with any number of arguments to another function

我正在尝试创建一个 C++ 函数,该函数接受具有任意数量参数的任何函数并将其传递给 std::thread 以启动一个线程。

#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);
}

是否可以创建一个 runFunctionInThread 函数,该函数适用于具有任意数量和任意类型的参数的任何函数?

使用它的一个variadic template with perfect forwarding参数,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(),例如:

int main()
{
    std::thread(&isolatedFunc1).detach();
    std::thread(&isolatedFunc2, 2).detach();
    std::thread(&isolatedFunc3, 3, 3).detach();
}