Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting value of type <T> into Variant, is it possible?

here is a snippet showing what I am trying to achieve:

type
  TMyObject<T> = class (TObject)
    function GetVarType(Value: T): TVarType;
  end;


function TMyObject<T>.GetVarType(Value: T): TVarType;
var
  TmpValue: Variant;
begin
  TmpValue := Variant(Value); //Invalid typecast
  Result := VarType(TmpValue);
end;

I know that above apporach with typecast is naive but I hope you get the idea. I would like to replace it with some conversion mechanism.

TMyObject will be always of simple type like Integer, String, Single, Double.

The purpose of such conversion is that function VarType gives me integer constant for each simple type which I can store somewhere else.

I would like to know if such conversion is possible?

Thanks for your time.

like image 202
Wodzu Avatar asked Oct 25 '11 15:10

Wodzu


1 Answers

It's trivially solvable in Delphis with enhanced RTTI (2010 and newer). Too bad you're limited to 2009 :(

function TMyObject<T>.GetVarType(Value: T): TVarType;
begin
  Result := VarType(TValue.From<T>(Value).AsVariant);
end;

This works only for simple types but that was a constraint specified in the question.

like image 145
gabr Avatar answered Nov 10 '22 00:11

gabr