Consider the following code:
template<typename T, size_t S> struct MyArray {
int length;
T contents_[S];
MyArray() { length = S; }
T& operator[](const int index) {
assert(index >= 0 && index < length);
return contents_[index];
}
int Length() { return length; }
};
Fundamentally, there is no reason to create separate copies of the Length functions and subscript operator for each value of S. But I'm concerned that in fact there will be duplication of these functions for each different value of S, limiting the usefulness of this approach.
(In case you are curious why I'm not using std::vector, it's because this is an embedded application without any heap based memory allocation)
MSVC uses "identical comdat folding" (ICF). This takes any two methods (or functions) with the same implementstion ... and uses the same function for them.
The gold linker for gcc (and clang apparently) also can do this (with varying degrees of aggressiveness).
Other than that, you'll have to do it manually.
or something less UB.