Get operator overloads

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 2 12:21:01 PDT 2014


On Tuesday, 2 September 2014 at 18:55:50 UTC, Ivan Timokhin wrote:
> Is it possible to get all overloads of an operator for a 
> particular type?
>
> I.e., having this struct definition, is it possible to tell at 
> compile time that it can be added with double and int[]?
>
> struct S
> {
>     void opBinary(string op : "+")(double);
>     void opBinary(string op : "+")(int[]);
> }
>
> To clarify, I am well aware that it can also be overloaded 
> through the second argument via opBinaryRight, but for now I'm 
> only interested in overloads provided by S itself.
>
> I've tried __traits(getOverloads), but with no success: 
> __traits(getOverloads, S, "opBinary") returns empty tuple,
> and __traits(getOverloads, S, `opBinary!"+"`) results in a 
> compilation
> error (dmd 2.065):
>
> Error: no property 'opBinary!"+"' for type 'S'
> Error: (S).opBinary!"+" cannot be resolved

I can't answer the question about inspecting the overloads, but 
if you just want to know whether it supports addition, the 
idiomatic way is to test whether it compiles:

     enum supportsAddition(S) = is(typeof(S.init + 0.0));

     static if(supportsAddition!MyType) { ... }


More information about the Digitalmars-d-learn mailing list