I'm repeatedly running into the problem of accepting a non-const reference parameter, since it seems taking an rvalue parameter prevents accepting lvalues and vice versa. Here's an example
void read(File &file)// I want to modify file
{
SomeClass someObject;
file.readInto(&someObject);//readInto is a non-const method
// do something with the data populated in someObject
}
But when I try to call read I have a problem if I try two different calling conventions
//this works just fine
File f1 = File::open("some_file_path");
read(f1);
// However this fails
read( File::open("some_file_path") );//because open returns an rvalue
The problem I have is if I change the parameter to a non-const rvalue than I can't pass the lvalue anymore. Am I doomed to always provide an override (or template) that takes the rvalue reference type and simply calls out to the lvalue override?
Since you updated the question, I suggest doing this:
That will handle both lvalues and rvalues with minimal code repetition.
I think your
read
function should simply take aFile&
:Then you can call:
Added benefit: the function is not limited to
shared_ptr
, and works with anyFile
independently of how its memory is managed.Alternatively, use a forwarding reference: