>>>> "Ben" == Ben Wing <ben(a)666.com>
writes:
Ben> What I don't want is to be able to pass one of them to a
Ben> function expecting the other -- but it *should* be possible
Ben> with an explicit cast, e.g. (Bytecount) x. Problem is, the
Ben> "cast operator" that can be defined on a class seems to
Ben> define implicit casts, not explicit. Is there any way to do
Ben> what I want?
I think this just wins as long as you make "just enough" effort. Make
user-defined conversions between ints and *counts, back and forth, but
_not_ between Bytecount and Charcount. This program does what you
want under g++ 2.95.4:
------------------------------- cut -------------------------------
typedef long int EMACSINT;
// I don't think these can be typedefs of instances of a common template
// class (they'd be the same class, then). Too lazy to try. But you could
// get the effect you want with a macro, of course.
class Charcount {
EMACSINT data;
public:
Charcount (EMACSINT i) { data = i; }
operator EMACSINT () { return data; }
};
class Bytecount {
EMACSINT data;
public:
Bytecount (EMACSINT i) { data = i; }
operator EMACSINT () { return data; }
};
extern void f (Bytecount b);
int main () {
Charcount c = 1;
f (Bytecount (c)); // wins, but ...
f (c); // *loses*
}
------------------------------- cut -------------------------------
The second call to f() loses because the interpretation must be
f (Bytecount (Charcount::operator int (c)));
which is rejected because both user-defined conversions are implicit.
The error is
test.cc:22: conversion from `Charcount' to non-scalar type `Bytecount' requested
There is an arbitrary restriction to at most one *implicit*
user-defined conversion in a conversion chain. The first call
f (Bytecount (c));
however, *wins* because now only the call to Charcount::operator int
is implicit.
Note, I don't have anything more recent than about 10 years old at
hand, either (Stroustrup and Ellis, 1e, and it's at home, to boot, so
everything above is ISTR). So you should check with a more recent
version of the standard (eg, Buchholz [2002] :^) to be sure. Not to
mention the compiler ;-)
--
Institute of Policy and Planning Sciences
http://turnbull.sk.tsukuba.ac.jp
University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN
Don't ask how you can "do" free software business;
ask what your business can "do for" free software.