This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Problem with "<<" operator



> Hi,
> I have a little problem with a class and the << operator:

Your code is wrong, but the compiler is wrong for being silent about it.

C++ never calls a function if you just mention that function's name.
If there are no arguments, you still have to say dummy(), not dummy.
In other contexts, the function's name is treated as a
pointer-to-function.  So what you are doing is converting a pointer
to the function dummy to a bool and passing the result to operator<<.

Write
	mc << dummy();

Ideally, the compiler should report at least a warning in this case.
I believe that the C++ standard now requires an explicit & to indicate
a pointer-to-function, so
	mc << dummy;
should be rejected, though I don't have my copy handy to point to chapter
and verse.

Sun CC 5.0 (a rather backward compiler) accepts the code, but HP aCC 
(a rather fussy mainly ISO-compliant compiler) prints

Error 226: "func.cxx", line 37 # No appropriate function found for call of
    'operator <<'. Last viable candidate was "MyClass &MyClass::operator
    <<(bool)" ["func.cxx", line 18]. Argument of type 'MyClass &(MyClass &)'
    could not be converted to 'bool'.
      mc<<dummy;
      ^^^^^^^^^ 

> // MyClass.h
> class MyClass
> {
>  .....
> public:
>   MyClass& operator<<(bool b);
> };
> 
> extern "C++"
> {
>   extern MyClass& dummy(MyClass &myclass);
> }
> 
> 
> 
> // MyClass.cpp
> MyClass& operator<<(bool b)
> {
>   // Do something
>   return(*this);
> }
> 
> MyClass& dummy(MyClass &myclass)
> {
>   myclass.AFunction();
>   return(myclass);
> }
> 
> 
> 
> // Main.cpp
> int main()
> {
>   MyClass mc;
> 
>   mc<<dummy;
> }
> 
> 
> The problem is that when I execute the code, the compiler generate a call to
> the operator<<(bool) and doesn't execute the code in the dummy function.
> -- 
> 
> 
> Ir. Pascal Francq
> Researcher
> Université Libre de Bruxelles
> Faculty of Applied Mechanics
> Avenue F.D. Roosevelt, 50
> CP 165/41
> B-1050 Brussels
> BELGIUM
> Tel. +32-2-650 47 65
> Fax +32-2-650 27 10
> 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]