ADL

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Sat Sep 3 10:40:08 PDT 2016


On Saturday, 3 September 2016 at 17:05:35 UTC, Tobias M wrote:
> On Saturday, 3 September 2016 at 16:32:16 UTC, ZombineDev wrote:
>> No you're wrong. There's no need for interfaces or for generic 
>> constraints. It's not static vs duck typing. It's just a 
>> method lookup issue. See for yourself: 
>> http://rextester.com/GFKNSK99121
>
> Ok, Interfaces and other generic methods with compatible 
> constraints.
> But in the end you cannot do much without any interface 
> constraints except writing out to the console as you do in the 
> example.
>
> But the main point still holds, name lookup is only done at 
> definition time, not at instantiation time. That's why you can 
> only call generic methods. Overloads don't work.

So what? C#'s generics are less flexible than C++ and D templates.
The point is that C#'s lookup does not consider only the 
implemented interfaces, but also falls back to extensions 
methods. If C# had ADL,
the compiler would also look for extension methods in the 
namespace
of the type (in non-generic methods, when the type is "known"), 
although the user of the type may not have imported the namespace.

>> Sum is implemented in that stupid way, because unlike C++, in 
>> C# operators need to be implemented as static methods, so you 
>> can't abstract them with an interface. If they were instance 
>> methods, you could implement them outside of the class as 
>> extension methods and there would be no need to write a 
>> distinct method for each type. Here's an example: 
>> http://rextester.com/PQFPC46087
>> The only thing missing is syntax sugar to forward the '+' 
>> operator to 'Add' in my example.
>
> With runtime reflection you can do almost anything... That's 
> circumventing the type system and doesn't disprove anything.

There's no circumventing the type system. `typeof(obj)` is barely 
even reflection. You can do this with regular cast or using the 
`is` expression (http://rextester.com/CXGNK69048). I used 
`typeof` just because it could yield better performance.

> I mean, it even "works" for types that cannot be added at all, 
> by just returning a default value...

? Sorry, I don't understand, what's the problem?


More information about the Digitalmars-d mailing list