Federico Zancan
Federico Zancan

Reputation: 4894

Ord function implementation in Delphi

Purely as an exercise at home, aimed to better understand some language basics, I tried to reimplement the Ord function, but I came across a problem.

In fact, the existing Ord function can accept arguments of a variety of different types (AnsiChar, Char, WideChar, Enumeration, Integer, Int64) and can return Integer or Int64.

I can't figure out how to declare multiple versions of the same function.

How should this be coded in Delphi?

Upvotes: 7

Views: 2854

Answers (2)

Rob Kennedy
Rob Kennedy

Reputation: 163357

Ord cannot be coded in Delphi. Although you can use the overload directive to write multiple functions with the same name, you cannot write the Ord function that way because it works for an arbitrary number of argument types without needing multiple definitions. (No matter how many Ord overloads you write, I can always come up with a type that your functions won't accept but that the compiler's will.)

It works that way because of compiler magic. The compiler knows about Ord and about all ordinal types in the program, so it performs the function's actions in-line. Other compiler-magic functions include Length (magic because it accepts arbitrary array types), Str (magic because it accepts width and precision modifiers), and ReadLn (magic because it accepts an arbitrary number of parameters).

Upvotes: 11

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

I can't figure out how to declare multiple versions of the same function.

It's called function overloading. Input parameters must be different for each version, return type doesn't matter. For example:

function Ord(X: Char): Integer; overload;
begin
  // Whatever here
end;

function Ord(X: Integer): Integer; overload;
begin
  // Something
end;

// etc.

Upvotes: 12

Related Questions