c++ 实现 cout 示例

#include <iostream>
#include <sstream>
#include <string>
class CMyStream {
    public:
        typedef void (CMyStream::* EndlCallback)();
        CMyStream& operator<<(EndlCallback pEndlCallback);

        template<typename T>
        CMyStream& operator<<(T Val) { //buffer the Val into stringstream
            std::stringstream ss;
            ss << Val;
            m_str += ss.str();
            return *this;
        }

        void MyEndl(); //use std::cout to output

    private:
        std::string m_str;
};

CMyStream::EndlCallback endl = &CMyStream::MyEndl;

CMyStream& CMyStream::operator<<(CMyStream::EndlCallback pEndlCallback) {
    (this->*pEndlCallback)();
    return *this;
}

void CMyStream::MyEndl(void) {
    std::cout << m_str << std::endl;
    m_str = "";
}

int main() {
    CMyStream cout;
    cout << "hello" << endl;
    cout << "world";//call CMyStream& operator<<(T Val)
    cout <<endl; // endl = &CMyStream::MyEndl 
    //=> so endl is a functor 
    //=> call CMyStream& operator<<(EndlCallback pEndlCallback) override 
    //=>  in function:     (this->*pEndlCallback)();
    //=> at last call to: void CMyStream::MyEndl(void){...}
    return 0;
}

原文链接: https://www.cnblogs.com/bigben0123/p/14081678.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/205699

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午10:19
下一篇 2023年2月12日 下午10:20

相关推荐