Making l-value from r-value
I've got quite a nifty get fnc which retu开发者_如何学JAVArns pointer to 'a type'. Now I would like to reuse this fnc in fnc set to set some value to this type returned by get:
template<class Tag,class Type>
set(Type t, some_value)
{
get<Tag>(t) = value;
}
The only problem I have is that: Because get returns pointer and not reference to a pointer the return type is a rvalue which for most cases is fine but not for this. Is there a way to somehow change the returned value into lvalue?
You can simply use this:
*get<Tag>(t) = value;
The result of dereferencing a pointer is an l-value.
Dereferencing a pointer (with the *
operator) yields a reference. The type of the reference depends on the type of the pointer. const T *
becomes const T &
, while T *
becomes T &
.
So, if get
returns a pointer to a non-const
variable, you can write:
*get<Tag>(t) = value;
If get
does not meet such requirement, and you can't change it, you'll have to give a set
method instead.
精彩评论