Given this prototype which does a Endian conversion:
time_t Flip( time_t );
I would like to use the return value in a function that takes a BYTE* as an argument. Something like this:
SetBytesAt( 0, (BYTE*)&(Flip( t )) );
But this does not compile. Gives me this error "& requires l-value". If the () are removed from around the Flip function, the same error is generated.
Now, I know that I can just do this:
time_t temp_t = Flip( t );
SetBytesAt( 0, (BYTE*)&temp_t );
But it seems to me that I should be able to accomplish the same thing without the temporary temp_t variable.
Unfortunately, no. You cannot take the address of a temporary (more correctly, an r-value). That's just the way the language has been defined.
Don't try this at home.
template <typename T>
class AddressableTemporary
{
public:
AddressableTemporary(T const value)
: value_(value)
{
}
operator T*() { return &value_; }
private:
T value_;
};
template <typename T>
AddressableTemporary<T> MakeAddressable(T value)
{
return AddressableTemporary<T>(value);
}
Used as:
int F() { return 42; }
void G(int const* const p) { std::cout << *p; }
int main()
{
G(MakeAddressable(F()));
}
But really, don't do this. Either use a variable, or write a wrapper function that encapsulates usage of the variable, or rework your code so that you don't need to worry about this (e.g., modify the function so that it takes, say, a const reference).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With