Search code examples
c++c++11function-pointersfunctorreference-wrapper

reference_wrapper Referencing Primitive


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

Solution

  • 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 >() );
    

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

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