将具有任意数量参数的任何函数传递给另一个函数 [英] Passing any function with any number of arguments to another function

查看:46
本文介绍了将具有任意数量参数的任何函数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

是否总有一个单一的 runFunctionInThread 函数可用于具有任意数量的参数和任何类型的任何函数?

Is there anyway to create a single runFunctionInThread function that works for any function with any number of arguments and any type?

推荐答案

使用变量模板及其参数的完美转发,例如:

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

这篇关于将具有任意数量参数的任何函数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆