我创建了一个自定义的 istream,它派生自 std::istream,在文件是压缩文件时使用自定义的 streambuf,在其他情况下使用 std::filebuf。
#mystream.h
class my_stream: public istream {
public:
explicit my_stream(const std::string &path);
private:
std::unique_ptr<std::streambuf> b_;
}
#mystream.cpp
my_stream::my_stream(const std::string &path) :std::istream(nullptr) {
if(path.substr(path.length()-6, path.length())==".gzip"){
b_ = std::make_unique<gzipbuf>(path); //gzipbuf is derived from std::streambuf
}
else {
std::unique_ptr<std::filebuf> fb;
fb->open(path.c_str(), std::ios::in);
b_ = fb;
}
this->init(b_.get());
}
我能够在一个地方将派生类的unique_ptr赋值给基类的unique_ptr
b_ = std::make_unique<gzipbuf>(path);
但不在另一个位置
b_ = fb;
它说:
candidate function not viable: no known conversion from 'unique_ptr<std::filebuf, default_delete<std::basic_filebuf<char>>>' to 'unique_ptr<std::basic_streambuf<char>, default_delete<std::basic_streambuf<char>>>' for 1st argument
operator=(unique_ptr&& __u) noexcept
b = std::move(fb);
,因为这里只能有一个对象(不能复制)。 - Galik