我的印象是,我可以使用reference_wrapper生成一个函子,该函子将返回传递给reference_wrapper ctor的对象。但这不管用。我做错了吗?如果是这样的话,是否有更好的方法来实现这一点?我可以写个朗姆达,好像我不应该写。
#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 );
}发布于 2014-04-02 12:32:37
因此,有一种方法可以使用std::integral_constant来实现这一点
const int thirteen = 13;
auto refWrap = bind( &std::integral_constant< int, thirteen >::operator int, std::integral_constant< int, thirteen >() );这确实解决了这个问题,但就所有意图和目的而言,它都不如lambda:
const int thirteen = 13;
auto refWrap = [=](){ return thirteen; };发布于 2014-03-07 17:51:14
成员变量也有类似的特性。也许你把它和那个搞混了。
struct foo { int bar; };如果有一个具有公共成员变量的类,则可以使用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';发布于 2014-03-07 17:26:32
std::reference_wrapper不生成函子。它只是一个函子,如果原始类型是Callable - std::reference_wrapper::operator()是可用的,只有当存储的引用是可调用的类型。
还不清楚为什么需要函子,但如果是这种情况,lambda可能是最简单的解决方案。
https://stackoverflow.com/questions/22256071
复制相似问题