c++ - 调用任何指定函数的函数

标签 c++

如何编写一个函数调用指定参数的任何指定函数(或函数对象)?

这是我尝试过的:

#include <iostream>
#include <functional>

using namespace std;

template <typename RetType, typename... ArgTypes>
RetType q(function<RetType(ArgTypes...)> f, ArgTypes... args)
{
    return f(args...);
}

int h(int a, int b, int c) { return a + b + c; }

int main()
{
    auto r = q(h, 1, 2, 3);

    cout << "called, result = " << r;

    return 0;
}

编译器说,由于类型“std::function<_Res(_ArgTypes ...)>”和“int (*)(int, int, int)”不匹配,模板参数推导/替换失败。

我不确定为什么不能在我的代码中推导出模板参数。

最佳答案

因为无论如何它都是一个模板,所以您根本不需要 std::function。只需这样做:

template <class F, class... Arg>
auto q(F f, Arg... arg) -> decltype(f(arg...))
{
  return f(arg...);
}

更好的是,使用完美转发:

template <class F, class... Arg>
auto q(F f, Arg&&... arg) -> decltype(f(std::forward<Arg>(arg)...))
{
  return f(std::forward<Arg>(arg)...);
}

关于c++ - 调用任何指定函数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31439909/

相关文章:

c++ - 获取类中静态属性的个数

java - 通过 getters-setters 在 C++ 中访问属性

c++ - 如何将值转换为 vector

c++ - C++中互斥锁和临界区之间的性能差异

c++ - C++ 中的灵活枚举

c++ - "std::size_t"在 C++ 中有意义吗?

c++ - 在 linux 中使用为 windows 编写的软件库(使用 dll)

c++ - FreeGlut(类似于 OpenGL)正在拍摄我的桌面而不是绘制形状

c++ - 在 C++ 中,(int *) 和 & 有什么区别?

c++ - std::optional<std::reference_wrapper<T>> - 可以吗?