获取 std::函数以推断按引用传递/按值传递
get std::function to deduce pass by reference/pass by value
我正在编写一个模板函数,该函数将 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,它将继续使用正确的引用类型。
相关文章:
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- 棘手的按值传递和按引用递归问题传递
- 不同于按值传递和常量引用传递的程序集
- 按值传递变量与按引用传递变量具有相同的结果
- 为什么按值传递QStringView比引用常量更快?
- 获取 std::函数以推断按引用传递/按值传递
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- C++按引用传递还是按值传递?
- 可移动但不可复制的对象:按值传递还是按引用传递?
- C++11 按 POD 类型的值传递比常量引用差
- 如何在 C++14 中编写用于调用 Fortran 函数的通用包装器(按引用调用 --按值调用>)
- 为什么编译器可以通过引用传递和值传递来重载函数
- 为什么要按 C++ 中的值传递对象
- C++:如何决定是按引用还是按值传递参数
- 迷失在通过引用、通过值传递的参数中
- 通过引用与通过值传递指向函数的指针,以及在指针链上使用delete
- c++按引用传递、值传递和Const问题
- 复制赋值运算符应该通过常量引用还是通过值传递
- 具有抽象基类的工厂模式 - 按引用或按值返回?范围界定和切片问题