"operator" overloading?

Jonathan M Davis jmdavisProg at gmx.com
Wed Feb 23 11:56:38 PST 2011


On Wednesday, February 23, 2011 10:42:04 Simon wrote:
> On 23/02/2011 14:37, Dmitry Olshansky wrote:
> > On 23.02.2011 17:08, %u wrote:
> >> Hi everyone,
> >> 
> >> Was hoping someone could help me make sense of this bit of C++ code:
> >> 
> >> class canvas
> >> {
> >> operator HDC() { return _hdc; }
> >> protected:
> >> canvas(HDC hdc): _hdc(hdc) {}
> >> HDC _hdc;
> >> }
> >> 
> >> From what I understand, HDC is an alias for HANDLE in Windows. So
> >> they are overloading canvas such that when assigned to handle
> >> instance it returns _hdc? How is this done in D?
> >> 
> >> Thanks
> > 
> > Something like this, and i shouldn't be a class in D (it's a proxy sort
> > of, right? ) :
> > 
> > struct canvas{
> > alias getHandle this;
> > this(HDC hdc){
> > _hdc = hdc;
> > }
> > @property HDC getHandle(){ return _hdc; }
> > private:
> > HDC _hdc;
> > }
> > 
> > uinttest{
> > HDC h = cast(HDC)1;
> > canvas c = h;//intitalize
> > h = c;
> > assert(h == c);
> > }
> 
> That's the wrong way round.
> 
> The c++ class is a canvas object which can be transparently passed to
> any windows function which takes a HDC.
> 
> Note the constructor is protected and the cast operator is public.
> 
> Not sure of the cast operator details in D though; I've never used it
> myself.

You can overload the cast operator in D:

    T opCast(T)() {...}

but it's for explicit cast only. There is not currently any way to do implicit 
casts with an overloaded operator. You have to use alias this for that, which 
may or may not do what be what you want if you want an implicit cast.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list