Replacement for C++ Style Implicit casts?
bearophile
bearophileHUGS at lycos.com
Mon Oct 18 14:03:36 PDT 2010
Mike Chaten:
> In C++ it is possible to declare a class as follows
> class Foo {
> Foo(int x) { }
> }
> You can then use that constructor to implicitly convert int to Foo. E.g
> Foo x = 0; //equivalent to Foo(0)
>
> Is there a way in D to do an implicit or explicit conversion from an
> integral type to a class?
Do you mean something like this?
class Foo {
int x;
static Foo opCall(int x_) {
auto f = new Foo;
f.x = x_;
return f;
}
}
void main() {
Foo f = Foo(5);
assert(f.x == 5);
}
(With structs it's simpler)
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list