获取 std::函数以推断按引用传递/按值传递

get std::function to deduce pass by reference/pass by value

本文关键字:按引用传递 按值传递 std 函数 获取      更新时间:2023-10-16

我正在编写一个模板函数,该函数将 std::function 作为输入并对函数进行一些处理。我想要一种自动处理任何函数的方法,但是我在类型推断中通过引用传递时遇到了问题。

我使用的函数类型是通用的,参数列表和类型都不同。这是一个复制者

#include <iostream>
#include <chrono> //c++11
#include <functional> //c++11
using namespace std;
// for use with functions passing by value
template<typename T_Out, typename... T_Args>
inline int get_stats( T_Out f(T_Args...), T_Args&... args)
{
f(args...);
return 0;
}
int foo(int x, double y)
{ return 0; }
int goo(int& x, double& y)
{ return 0; }
int hoo(int x , double& y)
{ return 0; }

int main()
{
int x = 42;
double y = 0.0;
cout << get_stats( foo, x, y) << endl;
return 0;
}

上面的模板适用于foo,如果我用f(T_Args&...)替换f(T_Args...),我可以让hoo工作,但是如果不显式编写模板来匹配传递类型,我就无法让hoo工作,在这一点上我可能根本不使用模板。

如何自动处理通过类型?此外,如果能够自动处理 prvalue,那就太好了。如果可能的话,我也想将其限制为 c++11。

实际上您需要结合前面的两个答案。KorelK 避免试图推断传递函子的确切签名的答案和 CJ13 使用完美转发的答案:

template<typename T_Func, typename ...T_Args>
inline int get_stats(T_Func f, T_Args&&... args)
{
return f(std::forward<T_Args>(args)...);
}

在线

template<typename T_Func, typename ...T_Args>
inline int get_stats(T_Func f, T_Args&&... args)
{
return f(args...);
}
int foo(int x, double y)
{ return x + y; }
int goo(int& x, double& y)
{ return x - y; }
int hoo(int x , double& y)
{ return x * y; }

int main()
{
int x = 42;
double y = 1.5;
cout << get_stats(foo, x, y) << endl;
cout << get_stats(goo, x, y) << endl;
cout << get_stats(hoo, x, y) << endl;
return 0;
}

为响应更好的解决方案而编辑:

这里要用的是斯科特·迈耶斯(Scott Meyers(所说的通用参考:

template<typename T_Out, typename... T_Args>
inline T_Out get_stats( T_Out f, T_Args&&... args)
{
return f(std::forward<T_Args>(args)...);
}

当模板参数后跟双 & 符号时,它将是左值引用或基于您传递它的右值引用。然后调用 std::forward,它将继续使用正确的引用类型。