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.