Creating a template mixin for explicit casts.

Sjoerd Nijboer sjoerdnijboer at gmail.com
Thu May 17 20:38:13 UTC 2018


On Thursday, 17 May 2018 at 16:27:48 UTC, Paul Backus wrote:
> On Thursday, 17 May 2018 at 15:25:37 UTC, Sjoerd Nijboer wrote:
>> I want to make a template mixin that is able to cast one of 
>> these generic structs to the other explicitly. I have a bunch 
>> of these structs and therefore I thought it would make sense 
>> to do it by template mixin. I just don't know what language or 
>> library features I need to use and how to apply them.
>
> It sounds like you want to overload opCast:
>
> https://dlang.org/spec/operatoroverloading.html#cast

Something like:
`
Foo!T opCast(U)(Foo!U old)
	if (isImplicitlyConvertible!(T, U))
	{
		return Foo!T(old.t);
	}

Foo!T opCast(UTemplate, U)(UTemplate!U old)
	if (isImplicitlyConvertible!(T, U) && isNumerical!U)
	{
		return Foo!T(old.t);
	}

`
But then how do you put this into a mixin template so I can write 
something like
`
struct Foo(T)
	if(isNumerical(T))
{
	mixin castingRules(typeof(this) T);
}
`


More information about the Digitalmars-d-learn mailing list