Reputation: 507
I am trying to create a generic class under delphi called TRange. The idea is that it can be a Range of Integer or a range of single, or Double, etc...
The TRange object contains a few variables of type T (maxValue, minValue, idealValue, etc). The TRange contains a function for each of them to convert them into a string. However, since Delphi is a strong-typed language, I need to specify "How-To" convert the different variables into a string.
I can get the typeName of the T type using GetTypeName (TypeInfo (T)). Once I know which type is T, I thought I could do something like:
if(className = 'single') then
result := formatFloat('0.0', self.AbsMin as Single)
else
result := intToStr(self.AbsMin as Integer)
However, the compiler tells me "Operator not Applicable to this operand Type".
So, I guess my question is :
Is there a way to give specificity to a generic Class???
Upvotes: 2
Views: 765
Reputation: 16620
The compiler error comes from the fact that you cannot use the as
operator to cast to a primitive type such as Single
or Integer
. Use a hard cast for that: Single(AbsMin)
.
Is there a way to give specificity to a generic Class???
Why do you need to convert the values to strings? This is kind of against the idea of a generic class, because you are now back to implementing special behaviour for all the cases.
If you really need this though you could introduce an interface
IValueStringConverter <T> = interface
function ToString(Value : T) : String;
end;
You can just supply the converter in the constructor of the TRange
class and store it in a field:
constructor TRange <T>.Create(Converter : IValueStringConverter <T>);
begin
FConverter := Converter;
end;
Now just use the converter inside the class to do the conversion:
Str := FConverter.ToString(AbsMin);
Upvotes: 6