samedi 29 août 2020

using C++11 templates to generate multiple versions of an algorithm

Say I'm making a general-purpose collection of some sort, and there are 4-5 points where a user might want to choose implementation A or B. For instance:

  • homogenous or heterogenous
  • do we maintain a count of the contained objects, which is slower
  • do we have it be thread-safe or not

I could just make 16 or 32 implementations, with each combination of features, but obviously this won't be easy to write or maintain.

I could pass in boolean flags to the constructor, that the class could check before doing certain operations. However, the compiler doesn't "know" what those arguments were so has to check them every time, and just checking enough boolean flags itself imposes a performance penalty.

So I'm wondering if template arguments can somehow be used so that at compile time the compiler sees if (false) or if (true) and therefore can completely optimize out the condition test, and if false, the conditional code. I've only found examples of templates as types, however, not as compile-time constants.

The main goal would be to utterly eliminate those calls to lock mutexes, increment and decrement counters, and so on, but additionally, if there's some way to actually remove the mutex or counters from the object structure as well that's be truly optimal.

Aucun commentaire:

Enregistrer un commentaire