创建模板函数以使用该功能参数调用其他函数

Create template function to call other functions with that functions parameters

本文关键字:函数 参数 功能 调用 其他 建模 创建      更新时间:2023-10-16

我想创建一个诸如 thread()函数(获取n参数)之类的函数。我想我必须使用这样的模板:

template <typename Func, typename Param1, ...>
void function(params)
{
}

但是,对于我的功能,我必须设置有限数量的参数。在thread()函数中,您可以给出此函数n参数。如何创建一个函数并在函数params中给出相同的参数?

template <typename Func, typename Param1, typename Param2, typename Param3 = typename()>
    void Remote_function_caller(Func Function_name, Param1 P1, Param2 P2, Param3 P3 = Param3())
{
Function_name(P1, P2, P3);
}
void Tool1(int Data1, int Data2)
{
}
void Tool2(int Data1, int Data2, int Data3)
{
}
void main()
{
      // Call tool 1
      Remote_function_caller(Tool1, 5, 6);
      // Call tool 2
      Remote_function_caller(Tool2, 5, 6, 9);
}

要调用 Tool1我必须输入2个参数,但是系统会出现错误,因为呼叫者需要3个参数(并加载该函数的3个参数)...

我建议使用 variadic模板

template<typename Func, typename... Params>
void function_caller(Func func, Params&&... params) {
    func(std::forward<Params>(params)...);
}

简短示例:

#include <iostream>
#include <utility>
template<typename Func, typename... Params>
void function_caller(Func func, Params&&... params) {
    func(std::forward<Params>(params)...);
}
void foo(int x, int y) {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void bar(int x, int y, int z) {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main() {
    function_caller(foo, 5, 6);
    function_caller(bar, 5, 6, 9);
    return 0;
}

输出为:

void foo(int, int)
void bar(int, int, int)