home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: defining cast operators outside classes
- Message-ID: <1992Sep8.173613.25113@taumet.com>
- Organization: TauMetric Corporation
- References: <TMB.92Sep7162324@arolla.idiap.ch>
- Date: Tue, 8 Sep 1992 17:36:13 GMT
- Lines: 68
-
- tmb@arolla.idiap.ch (Thomas M. Breuel) writes:
-
- >Apparently, it is impossible to define a conversion operator for a
- >class without making the conversion operator a member function.
-
- >It would be very useful to be able to define something like the
- >following without having to modify either class MyMatrix or class
- >TheirMatrix:
-
- > operator MyMatrix(TheirMatrix &m) {
- > ...
- > }
-
- >Why was this seemingly arbitrary restriction made? Can it be
- >eliminated in the next version of C++?
-
- In general, those operators which must be class members have that
- restriction to reduce the chance of subtle but serious bugs.
-
- Consider operator+(). If we write x+y, where x or y has a class
- type, and no operator+ is visible, the code will not compile. You
- must make a declaration visible. There is nothing subtle or
- dangerous about this.
-
- In the case of some operators you run the risk of having legal code
- with different meanings depending on whether the operator declaration
- is visible. In the case of user-defined conversions, consider this:
-
- class X {
- public:
- operator int();
- };
-
- X x;
- double y = x;
-
- extern operator double(const X&); // not legal
- double z = x;
-
- In this case, y gets "(double) X::operator int(x)",
- while z gets "operator double(x)".
-
- The semantics depend on which non-class declarations are visible,
- which is not normally the case in C++. (There is a somewhat
- parallel case: You omit one overloaded function declaration and
- an unintended function is called. Maybe someone can think of a way
- to solve that problem in the language.)
-
- In the case of conversions, it is likely that the conversion function
- would need to be a friend function, thus needing to appear in the
- class definition anyway.
-
- If you need to create an ad-hoc conversion from class A to class B
- when you don't own class A, you can make a B constructor taking an A.
- If you don't own class B either, you can write an ordinary function
- which does the conversion.
-
- In the end, the restriction elminates a source of dangerous but subtle
- bugs while creating virtually no extra inconvenience. The only
- inconvenience I can see occurs when ALL of these are met simultaneously:
- - You need to convert an A to a B.
- - You can't modify A or B.
- - Everything needed to do the conversion is public.
- - You want implicit conversion, not "b = A_to_B(a)".
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
- Vice Chair, ANSI C++ Committee, X3J16
-