www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Wrap + add methods?

reply Steven Schveighoffer <schveiguy gmail.com> writes:
I have a situation where I want to wrap a certain type to add a few 
methods to that type.

UFCS is not an option, because the library that will use this type will 
not import the UFCS methods.

`std.typecons.Proxy` doesn't seem to wrap static methods, and besides, I 
want to return wrappers if the function being wrapped returns the same 
type (this is critical for stuff like `auto result = a + b`, I want the 
result to be the same wrapped type).

Are there any libraries that might do this (including Phobos)?

-Steve
Jun 28 2021
parent reply Paul Backus <snarwin gmail.com> writes:
On Monday, 28 June 2021 at 15:17:34 UTC, Steven Schveighoffer 
wrote:
 I have a situation where I want to wrap a certain type to add a 
 few methods to that type.

 UFCS is not an option, because the library that will use this 
 type will not import the UFCS methods.

 `std.typecons.Proxy` doesn't seem to wrap static methods, and 
 besides, I want to return wrappers if the function being 
 wrapped returns the same type (this is critical for stuff like 
 `auto result = a + b`, I want the result to be the same wrapped 
 type).

 Are there any libraries that might do this (including Phobos)?
https://code.dlang.org/packages/addle Doesn't do everything you're looking for, but you might find some useful tricks in the source.
Jun 28 2021
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 6/28/21 11:53 AM, Paul Backus wrote:
 On Monday, 28 June 2021 at 15:17:34 UTC, Steven Schveighoffer wrote:
 I have a situation where I want to wrap a certain type to add a few 
 methods to that type.

 UFCS is not an option, because the library that will use this type 
 will not import the UFCS methods.

 `std.typecons.Proxy` doesn't seem to wrap static methods, and besides, 
 I want to return wrappers if the function being wrapped returns the 
 same type (this is critical for stuff like `auto result = a + b`, I 
 want the result to be the same wrapped type).

 Are there any libraries that might do this (including Phobos)?
https://code.dlang.org/packages/addle Doesn't do everything you're looking for, but you might find some useful tricks in the source.
Very neat! I think I can't use it, because I need to add static methods. My particular use case is a translated database type. In this case, it's a fixed point currency, which is stored as an integer in the database, but translated to a D fixedpoint type. To make it work with my DB library, I need to have a method `dbValue` which converts the D type into an appropriate D type that the database can utilize (long in this case), and a static method `fromDBValue` which goes the opposite direction. For now, I've just hand implemented the needed functions. This includes forwarding constructors, operator overloads, opAssign, etc. -Steve
Jun 28 2021