2

我反复遇到接受非常量引用参数的问题,因为似乎采用右值参数会阻止接受左值,反之亦然。这是一个例子

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
}

但是当我尝试调用 read 时,如果我尝试两种不同的调用约定,我会遇到问题

//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

我遇到的问题是,如果我将参数更改为非常量右值,那么我就不能再传递左值了。我是否注定总是提供一个采用右值引用类型并简单地调用左值覆盖的覆盖(或模板)?

4

1 回答 1

1

由于您更新了问题,我建议这样做:

void read(File& file)
{
    SomeClass someObject;
    file.radInto(&someObject);
    // ...
}

void read(File&& file) { read(file); }

这将以最少的代码重复处理左值和右值。


我认为您的read功能应该简单地采用File&

void read(File& file) // I want to modify file
{
    SomeClass someObject;
    file.readInto(&someObject);//Modifies file
    // do something with the data populated in someObject
}

然后你可以调用:

// OK
std::shared_ptr<File> f1 = File::open("some_file_path");
read(*f1);

// OK
read( *File::open("some_file_path") );

额外的好处:该函数不限于shared_ptr,并且可以与任何File独立于其内存管理方式的函数一起使用。


或者,使用转发参考

template <typename T>
void read(T&& file)// I want to modify file
{
    SomeClass someObject;
    file->readInto(&someObject);//Modifies file
    // do something with the data populated in someObject
}
于 2018-11-21T22:51:44.200 回答