cortoproject / corto

A hierarchical object store for connecting realtime machine data with web applications, historians & more
https://www.corto.io
MIT License
86 stars 14 forks source link

Add C++ template functions for enabling compile-time type safety #668

Closed SanderMertens closed 6 years ago

SanderMertens commented 6 years ago

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.

The resulting code would look like this:

Point *p = corto::declare<Point_t>(root_o, "p");

Which is equivalent to this C code:

Point *p = corto_declare(root_o, "p", Point_o);