Using << operator to write to both a file and cout

前端 未结 6 1106
滥情空心
滥情空心 2020-12-02 01:10

I\'d like to overload << operator to write the value it takes to a file and cout. I have tried to do it with following code, but couldn\'t succeed it. It just writes t

6条回答
  •  甜味超标
    2020-12-02 01:15

    Create a helper class and overload operators that takes care of streaming to two streams. Use the helper class instead of trying to override the standard library implementations of the overloaded operator<< functions.

    This should work:

    #include 
    #include 
    
    struct MyStreamingHelper
    {
        MyStreamingHelper(std::ostream& out1,
                          std::ostream& out2) : out1_(out1), out2_(out2) {}
        std::ostream& out1_;
        std::ostream& out2_;
    };
    
    template 
    MyStreamingHelper& operator<<(MyStreamingHelper& h, T const& t)
    {
       h.out1_ << t;
       h.out2_ << t;
       return h;
    }
    
    MyStreamingHelper& operator<<(MyStreamingHelper& h, std::ostream&(*f)(std::ostream&))
    {
       h.out1_ << f;
       h.out2_ << f;
       return h;
    }
    
    int main()
    {
       std::ofstream fl;
       fl.open("test.txt");
       MyStreamingHelper h(fl, std::cout);
       h << "!!!Hello World!!!" << std::endl;
       return 0;
    }
    

提交回复
热议问题