C++: How can i create a function that accepts concatenated strings as parameter?

前端 未结 4 1339
猫巷女王i
猫巷女王i 2021-01-18 14:34

Can i design my logging-function in a way, that it accepts concatenated strings of the following form using C++?

int i = 1;
customLoggFunction(\"My Integer i         


        
4条回答
  •  无人及你
    2021-01-18 14:51

    One approach is a simple utility class that uses a standard stream in a templated member function:

    class LogStream {
        public:
            template  LogStream& operator << (const T& rhs) {
                stream << rhs;
                return *this;
            }
    
        private:
            std::stringstream stream;
    };
    

    The stream member doing all the work is then used in the destructor,

    ~LogStream() {
        std::cout << stream.str() << std::endl;
    }
    

    and you can create temporary objects for passing your arguments to be concatenated:

    LogStream() << "anything with std::ostream operator: " << 1.2345 << ' ' << std::hex << 12;
    

    Additional state (e.g. a log level) can be passed to the constructor, often accompagnied by convenience functions like LogStream debug() { return LogStream(...); }. When you reach a certain point of sophistication though, you might want to switch to a logging library of course.

提交回复
热议问题