S
Simon Ford
Hi All,
I'm having trouble understanding exactly how I can do some specific implicit
casting. There are two problems here; does anyone know what I should be
doing?
//----------
// (1) Resolving as bool for comparison, but not as int.
//
// we have a class
class Foo{};
Foo x;
// I want to allow for a test of class Foo (i.e. returning bool)
if(x) {}
// which is probably done using : operator bool() const
// However, I don't want the compiler to allow this implicit cast
// to go through bool to int:
int y = 5;
int z = x + y; // should be an error
// i.e. z should not become 6, it should throw a compile error
// How do I allow the implicit boolean conversion without allowing
// the further integer conversion?
//----------
// (2) Casting from another type
//
// we have some operators overloaded:
bool operator== (Foo& lhs, Foo& rhs);
// Now, I would like to allow an implicit cast from another chosen type
// (string) to allow a comparison:
if(x == "bar") {} // "bar" is implicitly cast to a Foo of flavour bar
// i.e. avoiding having to define the two other variants for every operator
bool operator== (string lhs, Foo& rhs); // don't want to define this!
bool operator== (Foo& lhs, string rhs); // don't want to define this!
// How would I go about doing this?
//----------
Thanks for your time,
Simon ;o)
I'm having trouble understanding exactly how I can do some specific implicit
casting. There are two problems here; does anyone know what I should be
doing?
//----------
// (1) Resolving as bool for comparison, but not as int.
//
// we have a class
class Foo{};
Foo x;
// I want to allow for a test of class Foo (i.e. returning bool)
if(x) {}
// which is probably done using : operator bool() const
// However, I don't want the compiler to allow this implicit cast
// to go through bool to int:
int y = 5;
int z = x + y; // should be an error
// i.e. z should not become 6, it should throw a compile error
// How do I allow the implicit boolean conversion without allowing
// the further integer conversion?
//----------
// (2) Casting from another type
//
// we have some operators overloaded:
bool operator== (Foo& lhs, Foo& rhs);
// Now, I would like to allow an implicit cast from another chosen type
// (string) to allow a comparison:
if(x == "bar") {} // "bar" is implicitly cast to a Foo of flavour bar
// i.e. avoiding having to define the two other variants for every operator
bool operator== (string lhs, Foo& rhs); // don't want to define this!
bool operator== (Foo& lhs, string rhs); // don't want to define this!
// How would I go about doing this?
//----------
Thanks for your time,
Simon ;o)