Implementing the Ord Function in Delphi

Purely as an exercise at home aimed at better understanding some of the language basics, I tried to redefine the Ord function, but I ran into a problem.

In fact, the existing Ord function can take arguments of various types ( AnsiChar , Char , WideChar , Enumeration , Integer , Int64 ) and can return Integer or Int64.

I cannot figure out how to declare multiple versions of the same function.

How to code this in Delphi?

+6
source share
2 answers

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

This works because of the magic of the compiler. The compiler knows about Ord and all the ordinal types in the program, so it performs the actions of a function in a string. Other functions of the compiler magic include Length (magic, because it accepts arbitrary types of arrays), Str (magic, because it accepts modifiers of width and precision), and ReadLn (magic, because it accepts an arbitrary number of parameters).

+9
source

I cannot figure out how to declare multiple versions of the same function.

It caused an overload of functions . Input parameters should be different for each version, the type of return does not matter. For instance:

 function Ord(X: Char): Integer; overload; begin // Whatever here end; function Ord(X: Integer): Integer; overload; begin // Something end; // etc. 
+12
source

Source: https://habr.com/ru/post/911737/


All Articles