mardi 21 mai 2019

Use static_assert to ensure template parameters is only used at most once

Is it possible to ensure a certain template parameter value is used - at most - once? Would it be possible to track the number of times it's used, and throw a static_assert error if it was used more than once?

As an example - let's say I wanted to create a static, template-based GPIO class:

template<uint8_t Port, uint8_t Pin> class Gpio {};

One could feasibly lay out their entire board in a single Board class:

struct Board {
  Gpio<1, 1> myInputPin;
  Gpio<1, 2> myOutputPin;

  Gpio<2, 0> ledR;
  Gpio<2, 1> ledG;
  Gpio<2, 2> ledB;
};

It only makes sense for the GPIO template to be instantiated at most once, for a given port/pin combination. If someone creates two different GPIO instances for the same port/pin (especially if it's configured differently), I would like to catch this error during compilation.

Is this possible?

Aucun commentaire:

Enregistrer un commentaire