operator<<("foo"); It works...">

Operational deferred operator <<

Why it works well:

cout << "foo";

      

Is it not so yet?

(&cout)->operator<<("foo");

      

It works great with numeric values, so I think it has to do with overriding. (I am using the MS Visual C ++ compiler.)

+3


source share


3 answers


operator<<

is implemented as a member function for only a limited number of types. For other types, it is implemented as a global overload, for example:

std::ostream &operator<<(std::ostream &os, T const &t) { 
    // write the data here
}

      



The syntax you use will only work with overloads that are implemented as member functions, not globals.

+7


source


cout

has an overloaded member function operator<<(const void *)

. This is the best match for the argument "foo"

. ( const char*

implicitly converted to const void*

.) So the pointer will be printed.



// These call std::ostream& operator<<(std::ostream &os, const char * val)    
cout << "foo";
operator<<(cout,"foo");

// This calls cout member function operator<<(const void * val)
(&cout)->operator<<("foo");

      

+1


source


To get output like cout << "foo";

, you need to overload the operator <<

.

0


source







All Articles