函数引用通过std ::函数 [英] Functor reference through a std::function
本文介绍了函数引用通过std ::函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我想有以下语义:
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
}
我理解std :: function包装了一个可调用对象的副本,但是有什么办法使用std :: function来获取对可调用对象的引用?
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 :: ref
模板函数创建参考包装器:
std :: reference_wrapper
函数模板 ref
和 code> cref 是使用模板参数$ b $生成类型 std :: reference_wrapper
的
对象的助手函数
Function templates ref
and cref
are helper functions that generate an
object of type std::reference_wrapper
, using template argument
deduction to determine the template argument of the result.
您可以这样使用:
t.add(std::ref(t));
这篇关于函数引用通过std ::函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文