[英]Functor reference through a std::function
Basically, I would like to have the following semantic : 基本上,我想有以下语义:
#include <functional>
#include <iostream>
class test
{
public:
void add(std::function<void()> f)
{
f();
}
void operator()()
{
++x;
}
int x = 33;
};
int main()
{
test t;
t.add(t);
// wanted: x == 34 instead: x == 33 since add(t) copies it
}
I understand std::function wraps a copy of the callable object but is there any way to get a reference to a callable object using std::function? 我理解std :: function包装了一个可调用对象的副本,但有没有办法使用std :: function获取对可调用对象的引用?
You want to use the std::ref
template function to create a reference wrapper for your instance: 您想使用
std::ref
模板函数为您的实例创建一个引用包装器 :
std::reference_wrapper
is a class template that wraps a reference in a copyable, assignable object.std::reference_wrapper
是一个类模板,它在可复制的可分配对象中包装引用。Function templates
ref
andcref
are helper functions that generate an object of typestd::reference_wrapper
, using template argument deduction to determine the template argument of the result.函数模板
ref
和cref
是辅助函数,它们生成std::reference_wrapper
类型的对象,使用模板参数推导来确定结果的模板参数。
You would use it like this: 你会像这样使用它:
t.add(std::ref(t));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.