I’m trying to a design for a system where the user can define their own class as an aggregate of a number of predefined components, and then have this class work with algorithms which I provide. I am trying to do this with compile time and/or template based approaches rather than run time polymorphism or virtual functions as performance is important in this case.
For example, consider that I have a number of components which can be used to build a 3D vertex. I will define these components as Position, Normal, Color, etc, and then the user will be able (via multiple inheritance, composition, or what?) to define a vertex such as PositionAndColorVertex which has only position and color but no normal . Now, I provide a function which does some processing on a vector of one million these vertices:
template<typename UsersVertexType>
void myProvidedAlgorithm(std::vector<UsersVertexType> input)
{
if(vertex has a position)
//do stuff with position
if(vertex has a normal)
//do stuff with normal
if(vertex has a color)
//do stuff with color
}
Now, I don’t know what UsersVertexType will look like but it will be built from my components. My functions needs to do something with each of the components but only if they exist. What is an elegant and fast (compile time) way of expressing this?
Of course, I could define a base class for each type, make the user inherit from the desired base classes, and then use dynamic_cast to check which components are implemented, but this is exactly the sort of runtime approach I would like to avoid. Perhaps I can check this inheritance relationship at compile time (the compiler should know what UsersVertexType actually is, right?).
Perhaps my components should be expressed using C++ concepts or policies? I’ve also seen talk of mixins but not sure these are useful. Should the users class use multiple inheritance or composition? Maybe I should somehow get a set of flags into the users class, indicating what it contains? How would you design this system?
Thanks for any insight!
Note: There are similarities to my previous question, but here I am taking a step back and looking for higher level design options/alternatives.
Traits and template specializations.
Then define a version for your vertices with positional component, and one for vertices without:
Finally, for each vertex-type you define, implement a traits class:
… and have fun:
You could also specialize function templates, but would have to sacrifice some of the readability of your
shadefunction.