Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator << strange behaviour

Tags:

c++

stream

I have a class called Log, which overload the operator <<:

class Log
{
     public:
        static void init(std::ostream&);
        Log(const std::string&);
        ~Log(); //Write to the log here
        Log& operator<<(bool);
        Log& operator<<(const std::string&);

     private:
        std::stringstream text;
        static std::ostream *stream;
        std::string tag;
};

Ok, here is the problem, when i write to the log like this:

int main()
{
    std::ofstream file;
    file.open("log.txt",std::ios::app);
    Log::init(file);
    Log("[INFO]") << "Test";
    file.close();
}

The operator<< which receives a bool is called, that write true to the log..., if i delete the operator implementation which receives a bool then the other one is called correctly. I think this happens because the char* can be interpreted as bool... but how can i fix it??

like image 584
DGomez Avatar asked May 01 '26 11:05

DGomez


1 Answers

Create a third operator<< overload that takes a char * parameter.

I think your analysis of the problem is probably correct, although surprising.

like image 163
Mark Ransom Avatar answered May 03 '26 00:05

Mark Ransom