How smart are C++ compilers about code size with template classes?

108 views Asked by At

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)

1

There are 1 answers

3
Yakk - Adam Nevraumont On

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.

struct baseArray{
  int length=0;
  int Length() const { return length; }
};
template<class T>
struct buffBaseArray:baseArray{
  T& operator[](const int index) {
    assert(index >= 0 && index < this->length);
    return reinterpret_cast<T*>(this+1)[index];// todo// alignment and ub
  }
};
  
template<typename T, size_t S>
struct MyArray:buffBaseArray<T> {
  T contents_[S];
  MyArray() { length = S; }
 };

or something less UB.