ostream:在cout或文件上输出的类

时间:2019-06-10 06:14:00

标签: c++ ostream

我需要编写一个输出到std::cout或某个文件的程序。我正在阅读this post以了解操作方法。但是,我想将ostream的管理与main分开。所以我当时想写一个类,但对设计有些困惑。我有两个解决方案

  1. (公开)ostream的子类:这样,我将拥有所有ostream方法。但是,这里的主要问题是创建者:

    class sw_ostream : public ostream {
       sw_ostream (cost char* filename) : ostream ( \\? ) {
       \\ ...
       }
    \\...
    }
    

因为我应该根据ostream初始化filename,显然是不可能的。

  1. 创建一个以osteram为成员并重载operator<<的类。

我敢肯定,还有其他更优雅的解决方案可以解决此问题。您会建议哪种设计?

2 个答案:

答案 0 :(得分:2)

我会在这里尝试将流创建与流使用情况分开。 std :: ostream已经是多态的,因此只要您将引用或指针传递给使用该流的函数,就可以了。

对于创建,我将在您链接的帖子中建议在堆中创建流。但是,进行显式的内存管理(原始的新建/删除)很危险,因此我将使用智能指针,例如std :: unique_ptr:

#include <fstream>
#include <memory>

struct ConditionalDeleter
{
    bool must_delete;
    void operator()(std::ostream* os) const { if (must_delete) delete os; }
};

using OstreamPtr = std::unique_ptr<std::ostream, ConditionalDeleter>;

OstreamPtr create_stream(bool to_file)
{
    if (to_file)
        return OstreamPtr { new std::ofstream {"myfile.txt"}, ConditionalDeleter {true} };
    else
        return OstreamPtr { &std::cout, ConditionalDeleter {false} };
}

void use_stream(std::ostream& os)
{
    os << "Hello world!" << std::endl;
}

int main()
{
    auto streamptr = create_stream(false);
    use_stream(*streamptr);
}

我在std :: unique_ptr中使用了自定义删除器。这样做的原因是:如果我们正在使用文件,我希望删除流;但是std :: cout是一个全局对象,我们不能删除它。这里的协议是,当您的OstreamPtr被销毁时,将调用ConditionalDeleter :: operator()。 * streamptr返回您对std :: ostream的引用,您可以根据需要使用它。

请注意,使用此解决方案需要C ++ 11支持。

答案 1 :(得分:1)

由于它们都继承自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::fstreamSee here