reference_wrapper引用原语 [英] reference_wrapper Referencing Primitive

查看:259
本文介绍了reference_wrapper引用原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,我可以使用reference_wrapper来生成函数,函数将返回传递给reference_wrapper ctor的对象。但这不工作。我做错了吗?如果是这样,有更好的方法来完成这个?我可以写一个lambda,它只是看起来像我不应该。

I was under the impression that I could use reference_wrapper to generate a functor that would return the object passed into the reference_wrapper ctor. But this isn't working. Am I doing it wrong? If so is there a better way to accomplish this? I can write a lambda, it just seems like I shouldn't have to.

#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 );
}


推荐答案

使用 std :: integral_constant

So there is a way to accomplish this using std::integral_constant:

const int thirteen = 13;
auto refWrap = bind( &std::integral_constant< int, thirteen >::operator int, std::integral_constant< int, thirteen >() );

这解决了问题,但是对于所有的意图和目的来说都不如lambda:

This does solve the question, but for all intents and purposes is inferior to the lambda:

const int thirteen = 13;
auto refWrap = [=](){ return thirteen; };

这篇关于reference_wrapper引用原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆