Given

Given

function TRec.Foo(): S;
begin ... end;

Is there a way to generate a compile time error if T is different from S, but not if they are equal?

Comments

  1. Don't you want this then?
    function TRec. Foo() :T;

    ReplyDelete
  2. Nicholas Ring No, I specifically want the compile time error if S is not T. Assume S is not a descendant of T (or vice versa).

    ReplyDelete
  3. So you want it restricted to classes only? The reason I ask is because what if T is char and S is integer - neither having descendants?

    ReplyDelete
  4. Hm, lets say you can assume T is restricted to a class, ie
    function TRec.Foo(): S;

    S is specified by user, can be char, can be string, whatever. Just assume S is not a descendant of T.

    Hmm perhaps it is impossible, just testing where the borders go here :)

    ReplyDelete
  5. If T is restricted to class, then shouldn't S be restricted to class also? That would get you half way... 

    Edit: Can that be done?

    ReplyDelete
  6. Yeah I guess that'd be ok. Then what?

    ReplyDelete
  7. Assign a variable of T to a variable of S. If T and S are equal, theoretically, it'll compile. If they're not the same type, compile time error. ;o)

    ReplyDelete
  8. Also because S and T are the same type, you should also assign variable of S to variable of T.

    ReplyDelete
  9. If you play with class or interface, a constraint may be an option:
    TRec.Foo
    which constraints the S must be compatible with T.
    e.g. TRec.Create.Foo;

    Otherwise, I guess that you have to check TypeInfo(T) and TypeInfo(S) in the code.

    ReplyDelete
  10. Baoquan Zuo That won't trigger a compile time error as requested.

    ReplyDelete
  11. Uwe Raabe For class/interface types, it is compile time when specify the constraint. Otherwise, it is run-time. Actually, I think he needs to clearly defines what he want to do. Given a real context may be helpful.

    ReplyDelete
  12. CHUA Chee Wee That was my immediate thought, but it doesn't work, at least not in XE3. I assume the compiler actually creates some concrete internal types during parsing, which would obviously not be assignment compatible.

    Baoquan Zuo Just fooling with an idea for my library, and it probably sounds weird. Essentially T is specified by the library code (indirectly by the library user), and S by the library user. 

    I want to do something specific when they are equal, and otherwise let the user know he used the library wrong at compile time, rather than run-time.

    ReplyDelete

Post a Comment