Because corto_declare and corto_create both return a corto_object, in C++ this requires an application to do a cast when the return value is assigned to a typed value as C++ does not allow for implicit downcasting.
In combination with the code generator, a type safe mechanism can be built that automatically ensures that the right type object is passed to the corto_declare or corto_create, while also automatically casting to the right type.
There are two issues that arise when attempting this. First, the C++ template engine does not allow to concatenate arbitrary strings to the provided identifier (similar to ## in the C preprocessor), which makes it hard to resolve the type_o variable.
Secondly, depending on whether the type is a reference type or not, the function needs to return a pointer to the type, or the type itself.
These issues can be addressed by generating a class that looks like this:
class type_t {
public:
type *_ref; // a pointer when a value type, not a pointer when a reference type
static corto_struct _o; // points to the type object
}
The _t postfix is used to prevent name clashes with the actual type.
Because
corto_declare
andcorto_create
both return acorto_object
, in C++ this requires an application to do a cast when the return value is assigned to a typed value as C++ does not allow for implicit downcasting.In combination with the code generator, a type safe mechanism can be built that automatically ensures that the right type object is passed to the
corto_declare
orcorto_create
, while also automatically casting to the right type.There are two issues that arise when attempting this. First, the C++ template engine does not allow to concatenate arbitrary strings to the provided identifier (similar to
##
in the C preprocessor), which makes it hard to resolve thetype_o
variable.Secondly, depending on whether the type is a reference type or not, the function needs to return a pointer to the type, or the type itself.
These issues can be addressed by generating a class that looks like this:
The
_t
postfix is used to prevent name clashes with the actual type.The resulting code would look like this:
Which is equivalent to this C code: