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::reference_wrapper
doesn't generate functors. It is only a functor if original type isCallable
-std::reference_wrapper::operator()
is available only if stored reference is of callable type.It's not clear why you need the functor at all, but if it's the case then lambda might be simplest solution.
std::reference_wrapper::operator()
only participates in overload resolution if it's wrapping a callable object. Anint
isn't one, so what you're asking for won't work.You could do this:
Now you have a callable, the
bind
expression, and that can be invoked withinfunPtrPrinter()
.If I were you, I'd skip the middleman and pass in a lambda.
reference_wrapper
is only callable if the object it refers to is callable. Itsoperator()
simply calls the referenced callable object. If the object refered to is not callable thenoperator()
does not exist. In that sense it behaves just like a "real" reference.refWrap()
would be equivalent tothirteen()
, so ill formed.A similar feature exists for member variables. Maybe you confused it with that.
If you have a class with public member variables, you can use
std::mem_fn
andstd::bind
to create functors returning the value of the variable.So there is a way to accomplish this using
std::integral_constant
:This does solve the question, but for all intents and purposes is inferior to the lambda: