Ben Wing wrote:
I don't know C++ that well, and the book I have on it
(Stroustrop, 2nd
ed, I think) is 10 years old at least.
There's also a 3rd edition, which is not
just newer but IMHO generally
better...
XEmacs has typedefs such as Bytecount and Charcount. Currently they
are
just ints but I'd like to introduce some additional type-checking using
C++. In particular, I'd like to define them as classes, with the normal
operators overloaded in normal ways, and to allow free mixing (more or
less) between these types and ints (at the very least, it's reasonable
AFAIK
that's a language-pushing C++ problem which appears quite often; I
don't think there's any "best" solution (which is also typical :-) ),
but you can get close...
to pass constant ints to a function expecting a Bytecount or
Charcount).
What I don't want is to be able to pass one of them to a function
expecting the other -- but it *should* be possible with an explicit
cast, e.g. (Bytecount) x. Problem is, the "cast operator" that can be
OK, the following should do it:
=== cut ===
#include <iostream>
class Charcount;
class Bytecount
{
public:
Bytecount(int v):value(v) { }
explicit Bytecount(Charcount cc);
int toInt() { return value; }
private:
int value;
};
class Charcount
{
public:
Charcount(int v) { value = v ;}
explicit Charcount(Bytecount bc):value(bc.toInt()) { }
int toInt() { return value; }
private:
int value;
};
Bytecount::Bytecount(Charcount cc):
value(cc.toInt())
{
}
void f(Bytecount bc)
{
std::cout << bc.toInt() << std::endl;
}
void g(Charcount cc)
{
std::cout << cc.toInt() << std::endl;
}
int main()
{
Bytecount bc = 1;
Charcount cc(2);
f(3);
g(4);
f(bc);
// f(cc); will not compile
f((Bytecount)cc);
g(cc);
// g(bc); will not compile
g((Charcount)bc);
}
=== end cut ===
defined on a class seems to define implicit casts, not explicit. Is
there any way to do what I want?
You don't use cast operators, but conversion
constructors (or whatever
they're called), which *can* be made explicit.
Bye
Vasek