Is there a way to get the type of a generic variable in delphi at compile time? In C++ I'd do something like this:

Is there a way to get the type of a generic variable in delphi at compile time? In C++ I'd do something like this:

template
auto test(T x, T y) {

if (std::is_floating_point::value)
std::cout << "floating point" << std::endl;

if (std::is_integral::value)
std::cout << "integral point" << std::endl;

return x + y;
}

I'm using the library that does runtime checks. Can I do something similar in delphi? I have a generic class with some methods and I'd need to check the type values because there are different behaviors. I know that RTTI exists but it's at runtime

Comments

  1. Yes, use one of the intrinsic routines like GetTypeKind(). But performing any operations on a generic type will be very cumbersome because unlike C++ templates the compiler in Delphi wants those operation to be compatible to any type of T that you could use and you cannot restrict it to some type where you for example can perform addition on.

    My suggestion: don't try to mimic templates with Delphi generics and just write that code in C++ and call it from Delphi somehow if you need to.

    ReplyDelete
  2. I was wondering if Delphi had something similar so I could have achieved my goal faster. I guess I'll use RTTI or I'll find another way to do that.

    ReplyDelete
  3. Here is some example how such code would look like (and that code is far from correct for all possible types of T as it ignores size and signedness and assumes Integer and Int64):

    https://bitbucket.org/sglienke/spring4d/src/ca8037a2fdecbdbb23d3b997d1160f72838cee02/Source/Base/Collections/Spring.Collections.Base.pas#lines-1191

    ReplyDelete

Post a Comment