Is there an equivalent for C++:'template <typename T>' in DML?

90 views Asked by At

For this template, is it possible to parameterize the uint32 type?

template test_t {
    saved uint32 data;
}

I tried using param mytype = uint32, but did not work. Is it possible another way?

1

There are 1 answers

2
Love Waern On BEST ANSWER

DML doesn't have built-in support for generics, but you can emulate them by using param together with typeof. This, however, does have some notable shortcomings and is typically something you only reach for in desperation.

An example of how you'd emulate generics -- and to demonstrate the problems with doing so -- is the following:

template test_t {
    param data_type_carrier;
    #if (true) {
        saved typeof(data_type_carrier) data;
    }
}

group test is test_t {
    // safe as this expression is never evaluated
    param data_type_carrier = *cast(NULL, uint32 *);
}

That #if (true) probably sticks out to you: this is a hack to prevent DML from trying to make data part of the template type. Template types are evaluated and constructed at top-level, so object-local parameters are not in scope during their construction: without that #if (true) DML will reject the template, complaining that data_type_carrier is not in scope (this also applies to session.) Since data is made to not be part of the template type, this means you can't access it from a test_t value.

local test_t x = cast(test, test_t);
local uint32 y = x.data; // error

Similarly, you can't declare shared methods or typed parameters leveraging the parametrized type. Untyped parameters, non-shared methods, and subobjects are fair game, though, and as DML doesn't attempt to add such members to the template type you don't need the #if (true) hack for those.