Gerhard Sachs
Gerhard Sachs

Reputation: 21

Replacing overload by Generics in Delphi?

My question is very similar to 'How to use generics as a replacement for a bunch of overloaded methods working with different types?'

I tried the suggested solution GetRandomValueFromArray and it gives no complitetime errors. But the following does not compile :

Declaration / definition in existing class Tilib ..

    class function SetSingleBit<T>(const Value: T; const Bit: Byte): T;

    class function Tilib.SetSingleBit<T>(const Value: T; const Bit: Byte): T;
    begin
        Result := Value or (1 shl Bit);
    end;

Delphi 10.2 emits the error 'E2015 Operator ist auf diesen Operandentyp nicht anwendbar' (Operator not usable for the type of operand). Does anyone know whats wrong with that ?

Upvotes: 2

Views: 207

Answers (1)

David Heffernan
David Heffernan

Reputation: 613612

The problem is that T can be any type, and only certain types support the bitwise or operator.

It is possible to constrain generic types, so that the compiler knows more about their capabilities. For instance you can constrain the generic type to be a class, a sub class of a specific class, an interface, a value type, etc. But you cannot apply the constraint that you need, which would be that the type supports the bitwise or operator.

In short, the correct way to solve your problem is to use function overloading. Generics are not the solution to all problems.

Upvotes: 6

Related Questions