我的印象是我可以使用 reference_wrapper 生成一个仿函数,该仿函数将返回传递给 reference_wrapper 构造函数的对象。但这不起作用。我做错了吗?如果是这样,是否有更好的方法来实现这一目标?我可以编写一个 lambda,看起来我不应该这样做。
#include <iostream>
#include <functional>
using namespace std;
void funPtrPrinter( function< int( void ) > output )
{
cout << output() << endl;
}
int main( void )
{
int thirteen = 13;
auto refWrap = ref( thirteen );
funPtrPrinter( refWrap );
}
最佳答案
成员变量也有类似的特性。也许你把它和那个搞混了。
struct foo { int bar; };
如果您有一个带有公共(public)成员变量的类,您可以使用 std::mem_fn
和 std::bind
创建返回变量值的仿函数。
auto f = std::mem_fn(&foo::bar);
std::cout << f(foo{42}) << '\n';
auto g = std::bind(&foo::bar, foo{42});
std::cout << g() << '\n';
关于c++ - reference_wrapper 引用原语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22256071/