Conditionally Define a Variable within a Template Class

Hi all. I’m working on a library class that contains an internal array of objects (in my example below, those objects are just uint8_t). The library’s user needs to be able to specify the number of objects in said array.

One way to do this would be to malloc() the array in the class’s constructor. But then the user does not get any feedback from the compiler about whether there’s enough RAM to accommodate the size requested. So, I thought of using a template (which I’m very inexperienced at):

template<uint16_t NUM_ELEMENTS>
class NewClass1 {
  private:
    uint8_t internalArray[NUM_ELEMENTS];
};

NewClass1<100> newObject1;  // Intantitate object with array size 100

void setup() {}

void loop() {}

No problems so far. But, now I want to OPTIONALLY create a second array (of the same size) inside the class. Again, I’d like the user to be able to specify whether or not to create this second array when an object of the template class is instantiated. I’ve shown this conceptually below, but the code is obviously wrong:

template<uint16_t NUM_ELEMENTS, bool EXTRA_ARRAY = false>
class NewClass2 {
  private:
    uint8_t internalArray[NUM_ELEMENTS];

#if EXTRA_ARRAY
    uint8_t extraArray[NUM_ELEMENTS];
#endif

};

NewClass2<100> newObject1;    // Instantiate object with single internal array of 100 elements
NewClass2<100, true> newObject2;  // // Instantiate object with two internal arrays of 100 elements each

void setup() {}

void loop() {}

So, finally, the question – is there any way to do this “conditional” variable definition inside a template class?

Thanks.

You can use template specialization, like this:

// Class template "signature", like a prototype
template<uint16_t NUM_ELEMENTS, bool EXTRA_ARRAY = false >
class NewClass2;

// Specialize for EXTRA_ARRAY = false
template<uint16_t NUM_ELEMENTS>
class NewClass2<NUM_ELEMENTS, false > {
  private:
    uint8_t internalArray[NUM_ELEMENTS];
    // No extra array
};

// Specialize for EXTRA_ARRAY = true
template<uint16_t NUM_ELEMENTS>
class NewClass2<NUM_ELEMENTS, true > {
  private:
    uint8_t internalArray[NUM_ELEMENTS];
    // With extra array
    uint8_t extraArray[NUM_ELEMENTS];
};

NewClass2<100> newObject1;    // Instantiate object with single internal array of 100 elements
NewClass2<100, true> newObject2;  // // Instantiate object with two internal arrays of 100 elements each

void setup() {}

void loop() {}

giova014:
You can use template specialization

Thanks!!! I did run across that concept in my web searching, but couldn't figure out how to apply it. The syntax is daunting.