opCast / operator overloading with additional template arguments

Ali Çehreli acehreli at yahoo.com
Mon Jan 11 00:25:36 UTC 2021


On 1/10/21 4:09 PM, Paul wrote:

 > Is there a way to have additional template arguments in operator 
overloads?

I haven't tried that but the following method seems to work for you. You 
don't show complete code; so, I hope I came up with something that 
reflects your case.

import std;

struct S(T) {
   auto opCast(U)() const
   if (isInstanceOfS!U) {
     writefln!"Converting from %s to %s"(S.stringof, U.stringof);
     return U.init;
   }
}

enum isInstanceOfS(T) = isInstanceOf!(S, T);

void main() {
   auto a = S!int();
   auto b = cast(S!double)a;  // Works
   auto c = a.to!(S!double);  // This works too
}

I needed the isInstanceOfS wrapper over std.traits.isInstanceOf because 
I could not use isInstanceOf inside the definition of S because the 
symbol 'S' does not mean "the template S", but the specific 
instantiation of it e.g. S!int. Outside, S means "the template S".

Ali



More information about the Digitalmars-d-learn mailing list