Hello there

Hello there,

Is this a bug or a feature? Calling a generic method w/o specifying the generic type. It works like a charm

type
Foo = record
public
class procedure SayIntfName(const Value: T); static;
class procedure SayClassName(const Value: T); static;
end;

class procedure Foo.SayIntfName(const Value: T);
var
ctx: TRttiContext;
begin
Writeln(ctx.GetType(TypeInfo(T)).Name);
end;

class procedure Foo.SayClassName(const Value: T);
var
ctx: TRttiContext;
begin
Writeln(ctx.GetType(TypeInfo(T)).Name);
end;

var
Bar: IInvokable;
Zod: TStringBuilder;
begin
Foo.SayIntfName(Bar);
Foo.SayClassName(Zod);
Readln;
end.

Comments

  1. Normally, one would call

    Foo.SayIntfName;
    Foo.SayClassName;

    ReplyDelete
  2. Feature (I believe). The compiler (I guess) can figure out the type and pass it on.

    I hope it is a feature (as we rely on it at work). ;-)

    ReplyDelete
  3. It's a feature called type deduction, and the compiler could be a lot smarter about it so we didn't have to type so much "noise".

    ReplyDelete
  4. If the compiler can do the type inference, you don't need to specify the type. But I agree with Asbjørn Heid on the smartness: some other compilers are way better at generic type inference.

    ReplyDelete
  5. While in C++ templates this is called type deduction I think the general term is called type inference (see https://en.wikipedia.org/wiki/Type_inference). As you see in the article this does not only apply to generics but also in other parts where the compiler can determine the type of an expression so you don't have to be explicit.

    P.S. Why get the TRttiType when PTypeInfo already knows the name?

    ReplyDelete
  6. Well, I'm not sure it's a feature or an "accident". So, the if compiler is able to do type inference, why not enable that feature everywhere?

    Stefan Glienke​ good catch. Thought didn't cross my mind :)

    ReplyDelete
  7. Agustin Ortu What do you mean by "everywhere"?

    ReplyDelete
  8. It's a feature in relation to generic types that can be determined by the compiler by the passed argument. If you don't have an already typed argument for the generic parameter the compiler cannot do inference. Using type inference for variable types is a completely different story because it would require assigning values where variable is declared.

    Agustin Ortu Sad - I see similar patterns used in the RTL as well lately... :(

    ReplyDelete
  9. DWScript has type inference for variables. IMHO it's great but it does need functioning CodeInsight or you'll have to hit F9 a lot more. And Delphi never had functioning CodeInsight.

    ReplyDelete

Post a Comment