opCast / operator overloading with additional template arguments

Paul paultjeadriaanse at gmail.com
Mon Jan 11 00:09:43 UTC 2021


Is there a way to have additional template arguments in operator 
overloads?
The problem I'm having is mostly caused by casting a templated 
struct to other templated structs. I had the following code;

> T opCast(T)() const if (is(T : Vec!(vecsize, S), S)) {
> 	T converted;
> 	static foreach (i; 0 .. vecsize)
> 		converted.content[i] = cast(S) content[i];
> 	return converted;
> }

When I try to use this, I get the error 'undefined identifier S'.
Alternatively using:
> T opCast(T, S)() . . .
causes the error 'template instance opCast!(Vec!(2, double)) does 
not match template declaration opCast(T, S)()'

I found using 'alias S = typeof(content[0])' works as a kind of 
ducttape alternative, however this seems like a codesmell to me, 
and I fear it won't scale well either.

Am I missing a simple solution? And why is there no automatic 
argument deduction in this scenario when compared to normal 
function calls? (if the above opcast is translated to 
'foo.opCast!T`)


More information about the Digitalmars-d-learn mailing list