由于它们都继承自 std::ostream,因此您只需将其分配给 std::ostream&。
在你的情况下,你可以简单地做这样的事情:
#include <iostream>
#include <fstream>
void do_stuff(const char* filename = nullptr) {
std::ofstream _f;
std::ostream& os = filename ? (_f.open(filename), _f) : std::cout;
os << "Output normally";
// If you want to check if it is a file somewhere else
if (std::ofstream* fp = dynamic_cast<std::ofstream*>(&os)) {
std::ofstream& f = *fp;
// But here you can probably check the condition used to make the file
// (e.g. here `filename != nullptr`)
}
// After returning, `os` is invalid because `_f` dies, so you can't return it.
}
一个更简单的方法是完全不用担心这个。只需将所有输出内容的代码放在一个接受std::ostream& 参数的函数中,然后使用std::ofstream 或另一个std::ostream 调用它:
void do_stuff(std::ostream& os) {
os << "Write string\n";
}
int main() {
if (using_file) {
std::ofstream f("filename");
do_stuff(f);
} else {
do_stuff(std::cout);
}
}
如果您希望能够在不关闭文件并成为悬空引用的情况下返回对象,则需要将其存储在某个地方。此示例将其存储在结构中:
#include <iostream>
#include <fstream>
#include <utility>
#include <new>
#include <cassert>
struct sw_ostream {
private:
// std::optional<std::fstream> f;
// Use raw storage and placement new pre-C++17 instead of std::optional
alignas(std::fstream) unsigned char f[sizeof(std::fstream)];
std::ostream* os;
bool did_construct_fstream() const noexcept {
// If `os` is a pointer to `f`, we placement new`d, so we need to destruct it
return reinterpret_cast<unsigned char*>(os) == f;
}
// Destroys currently held std::fstream
// (Must have been constructed first and have `os` point to it)
void destruct() noexcept {
static_cast<std::fstream&>(*os).~basic_fstream();
}
public:
sw_ostream() = default;
sw_ostream(std::ostream& os_) : os(&os_) {}
template<class... Args>
explicit sw_ostream(Args&&... args) {
os = new (f) std::fstream(std::forward<Args>(args)...);
}
sw_ostream(std::fstream&& f) : os(nullptr) {
*this = std::move(f);
}
sw_ostream(sw_ostream&& other) noexcept {
*this = std::move(other);
}
sw_ostream& operator=(sw_ostream&& other) {
if (did_construct_fstream()) {
if (other.did_construct_fstream()) {
static_cast<std::fstream&>(*os) = std::move(static_cast<std::fstream&>(*(other.os)));
} else {
destruct();
os = other.os;
}
} else {
if (other.did_construct_fstream()) {
os = new (f) std::fstream(std::move(static_cast<std::fstream&>(*other.os)));
} else {
os = other.os;
}
}
return *this;
}
sw_ostream& operator=(std::ostream& other) {
if (did_construct_fstream()) {
destruct();
}
os = &other;
return *this;
}
sw_ostream& operator=(std::fstream&& other) {
if (did_construct_fstream()) {
static_cast<std::fstream&>(*os) = std::move(other);
} else {
os = new (f) std::fstream(std::move(other));
}
return *this;
}
std::ostream& operator*() const noexcept {
return *os;
}
std::ostream* operator->() const noexcept {
return os;
}
operator std::ostream&() const noexcept {
return *os;
}
std::fstream* get_fstream() const noexcept {
if (did_construct_fstream()) return &static_cast<std::fstream&>(*os);
return dynamic_cast<std::fstream*>(os);
}
// `s << (...)` is a shorthand for `*s << (...)` (Where `s` is a `sw_ostream`)
template<class T>
const sw_ostream& operator<<(T&& o) const {
*os << std::forward<T>(o);
return *this;
}
template<class T>
sw_ostream& operator<<(T&& o) {
*os << std::forward<T>(o);
return *this;
}
~sw_ostream() {
if (did_construct_fstream()) {
destruct();
}
}
};
int main() {
sw_ostream s;
if (opening_file) {
s = std::fstream("filename");
} else {
s = std::cout;
}
if (std::fstream* fp = s.get_fstream()) {
assert(fp->is_open());
}
s << "Hello, world!\n";
s->flush();
}
我还提出了另一个使用std::unique_ptr 的解决方案,这样您就可以使用std::ostream 的任何派生类,但是如果您只想要现有的std::ostream(如std::cout)或std::fstream。 See here.