Ben Wing <ben(a)666.com> writes:
possible with an explicit cast, e.g. (Bytecount) x. Problem is, the
"cast operator" that can be defined on a class seems to define
implicit casts, not explicit. Is there any way to do what I want?
Yes you can.. C++ has an "explicit" keyword for this purpose.
The below example does it by defining an explicit copy constructor and
letting the compiler generate the conversion operators from that.
[Note that if you allow the uncommented conversions to int below, you
not strictly need the explicit copy constructors as]
struct charcount;
struct bytecount;
struct charcount {
int count;
charcount() { }
charcount(int i) : count(i) { }
// Allow type conversions
explicit charcount(bytecount bc);
int getcount() { return count;}
// operator int() { return getcount(); }
};
struct bytecount {
int count;
bytecount() { }
bytecount(int i) : count(i) { }
// Allow explicit type conversions through copy
explicit bytecount(charcount cc) : count(cc.getcount()) { }
int getcount() { return count ;}
// operator int() { return getcount(); }
};
inline charcount::charcount(bytecount bc) : count(bc.getcount()) { }
void foo(bytecount b);
int main()
{
bytecount b1 = 50;
bytecount b2;
charcount c1 = 100;
// Explit conversions (C style)
c1 = (charcount)b1;
b2 = (bytecount)c1;
foo((bytecount)c1);
// Explict conversion (C++ style)
c1 = charcount(b1);
b2 = bytecount(c1);
// Conversion to int works if the convertor operators are defined above
// int i1 = c1;
// int i2 = b1;
// These fail to compile because
// 1. We made the copy contructor explicit
// 2. Convertsion via int requires two conversions, if defined
c1 = b1;
b2 = c1;
foo(c1);
}
cd /tmp/
g++-3.0 bytecount.cpp -o bytecount
bytecount.cpp: In function `int main()':
bytecount.cpp:49: no match for `charcount& = bytecount&' operator
bytecount.cpp:5: candidates are: charcount& charcount::operator=(const
charcount&)
bytecount.cpp:50: no match for `bytecount& = charcount&' operator
bytecount.cpp:16: candidates are: bytecount& bytecount::operator=(const
bytecount&)
bytecount.cpp:51: conversion from `charcount' to non-scalar type `bytecount'
requested
Compilation exited abnormally with code 1 at Sun Apr 14 16:28:06