Topic: Constructor vs conversion operator in ambiguity resolution


Author: jamshid@io.com (Jamshid Afshar)
Date: 1996/03/13
Raw View
I just want to verify that the below code is an ambiguity error.  VC++
4.0 accepts the code.  The rules haven't changed recently in this
regard, have they?  Btw, g++ 2.6.3 also accepts the code, but it calls
operator<<(ostream&, const char*).

// VC++ should be flagging the "cout << cs;" line below as an
// ambiguity error because converting a CString to a "const char*" is
// an equivalent match to using it to construct a temporary Foo.  But,
// VC++ silently accepts and chooses to construct a temporary Foo.
// A workaround is to define an operator<<(ostream&,const CString&),
// which really should be defined by MFC anyway.

#include <iostream.h> // defines operator<<( ostream&, const char* )

class CString {
    const char* _s;
public:
    CString( const char* s ) : _s(s) {}  // obviously just for demonstration
    operator const char*() const { return _s; }
};

class Foo {
public:
    Foo( const CString& ) {}
    friend ostream& operator<<( ostream& os, const Foo& f )
    { return os << "This is a Foo." << endl; }
};

int main() {
    CString cs = "this is a CString";
    cout << cs;  // error: ambiguous, but VC++ silently accepts using Foo ctor
    cout << endl;
    return 0;
}
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]