Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 函数调用任何指定的函数_C++ - Fatal编程技术网

C++ 函数调用任何指定的函数

C++ 函数调用任何指定的函数,c++,C++,如何使用指定参数编写调用任何指定函数(或函数对象)的函数 以下是我尝试过的: #include <iostream> #include <functional> using namespace std; template <typename RetType, typename... ArgTypes> RetType q(function<RetType(ArgTypes...)> f, ArgTypes... args) { retu

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

以下是我尝试过的:

#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;
模板
RetType q(函数f,ArgTypes…args)
{
返回f(args…);
}
inth(inta,intb,intc){返回a+b+c;}
int main()
{
自动r=q(h,1,2,3);

cout因为它是一个模板,所以您根本不需要
std::function
。只需执行以下操作:

template <class F, class... Arg>
auto q(F f, Arg... arg) -> decltype(f(arg...))
{
  return f(arg...);
}
模板
自动q(F,Arg…Arg)->decltype(F(Arg…)
{
返回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)...);
}
模板
自动q(F,Arg&&…Arg)->decltype(F(std::forward(Arg)…)
{
返回f(标准:正向(参数)…);
}

对于一个简单的问题,您可能正在走一条艰难的道路。。。 您可以只使用闭包,不带任何参数

#include <iostream>
#include <functional>

using namespace std;

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

int main()
{
    auto clsr = [](){ return h(1, 2, 3); };

    auto r = clsr();
    cout << "called, result = " << r;
    return 0;
}
#包括
#包括
使用名称空间std;
inth(inta,intb,intc){返回a+b+c;}
int main()
{
auto-clsr=[](){返回h(1,2,3);};
自动r=clsr();

您是否可以尝试在
h
上使用
make_函数
:因为C++14,由于返回类型的推导,指定尾部返回类型是不必要的,所以
auto q(F F,Arg&…Arg)
就足够了。