Custom manipulator for C++ iostream

前端 未结 4 1535
Happy的楠姐
Happy的楠姐 2020-11-29 02:44

I\'d like to implement a custom manipulator for ostream to do some manipulation on the next item being inserted into the stream. For example, let\'s say I have a custom mani

4条回答
  •  再見小時候
    2020-11-29 03:13

    Try this:

    #include 
    #include 
    
    // The Object that we put on the stream.
    // Pass in the character we want to 'quote' the next object with.
    class Quote
    {
        public:
            Quote(char x)
                :m_q(x)
            {}
        private:
            // Classes that actual does the work.
            class Quoter
            {
                public:
                    Quoter(Quote const& quote,std::ostream& output)
                        :m_q(quote.m_q)
                        ,m_s(output)
                    {}
    
                    // The << operator for all types. Outputs the next object
                    // to the stored stream then returns the stream. 
                    template
                    std::ostream& operator<<(T const& quoted)
                    {
                        return m_s << m_q << quoted << m_q;
                    }
    
                private:
                    char            m_q;
                    std::ostream&   m_s;
            };
            friend Quote::Quoter operator<<(std::ostream& str,Quote const& quote);
    
        private:
            char    m_q;
    };
    
    // When you pass an object of type Quote to an ostream it returns
    // an object of Quote::Quoter that has overloaded the << operator for
    // all types. This will quote the next object and the return the stream
    // to continue processing as normal.
    Quote::Quoter operator<<(std::ostream& str,Quote const& quote)
    {
        return Quote::Quoter(quote,str);
    }
    
    
    int main()
    {
        std::cout << Quote('"') << "plop" << std::endl;
    }
    

提交回复
热议问题