c++ - 创建模板函数以使用该函数参数调用其他函数

标签 c++ c++11 templates

我想创建一个类似于thread() 函数的函数(获取N 个参数)。我想我必须使用这样的模板:

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

}

但是对于我的函数,我必须设置有限数量的参数。在 thread() 函数中,您可以为该函数提供 N 个参数。如何创建一个函数并在函数参数中赋予相同的参数?

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 个参数加载该函数)...

最佳答案

我建议使用可变参数模板:

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)

关于c++ - 创建模板函数以使用该函数参数调用其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41269998/

相关文章:

c++ - 如何有效地从 C++ 中的集合中删除开始和结束元素?

c++ - 在 lambda 中捕获完美转发的变量

c++ - VS2008 SP1 中的 Lambda 表达式支持

c++ - Derived对象调用Base方法的模板推导

C++ 给出大量奇怪的答案(afaik 不会溢出)

c++ - docker 容器中的 gdb 返回 "ptrace: Operation not permitted."

c++ - "Invalid initialization of non-const reference of type ' std::vector& ' from an rvalue of type ' std::vector"错误

c++11 注册缓存线程安全

c++ - 错误 : ‘SIZE’ cannot appear in a constant-expression when using template< class T, int MAX_SIZE >

c++ - 如何创建一个类,使 vector 起作用std::vector <MyClass <int >> v {1,2,3};