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

前端 未结 4 1386
猫巷女王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 15:07

    You could do it by defining a new operator<<. From vague memory, implementing functions with these three signatures will do the trick:

    std::string operator<<(const char * a, const std::string & b);
    std::string operator<<(const std::string & a, const char * b);
    std::string operator<<(const std::string & a, const std::string & b);
    

    Each of them has to concatenate its arguments and return a std::string.

    Howeever, it feels wrong. Goes against the grain of C++. I suggest a more C++-ish solution, namely to make your logger into a class, and write operator<<() members for that class, so you can run

    customLog << "My Integer i = " << i << "." << "\n";
    

提交回复
热议问题