4 ms·
One of the reasons I like C++ is that it lets you throw away type safety and still maintain it through abstraction. This sounds awful, so let me explain. In on
by k4st 14y ago
One of the reasons I like C++ is that it lets you throw away type safety and still maintain it through abstraction. This sounds awful, so let me explain.
In one project, I implemented an EDSL for performing a destructuring bind on a string (CFG production, actually). The types of the components of the pattern determined what the pattern would actually match.
This was all done in a previous version of C++, so I didn't have variadic templates available. I also didn't want to heap allocate the internals of patterns.
What I did was to store an array of void pointers and a function pointer as private fields within a pattern class. When constructing the pattern, pointers to the things to which parts of the string to be bound were put into the array, thus throwing away their types. BUT, the function pointer pointed to a static method in of a class template, which only operated on the array of void pointers in a type-safe way, precisely because it was compiled with the knowledge of the types.
I use this type of subversion when appropriate, and it's often a very convenient solution to an otherwise tricky problem. Such a thing would either not be possible--or be incredibly inconvenient--in C. It's often very useful to treat different stuff uniformly, knowing that your abstractions can maintain type safety.