3

考虑以下代码:

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; }

};

从根本上说,没有理由为 S 的每个值创建长度函数和下标运算符的单独副本。但我担心实际上每个不同的 S 值都会重复这些函数,从而限制了它的有用性方法。

(如果你好奇我为什么不使用 std::vector,那是因为这是一个没有任何基于堆的内存分配的嵌入式应用程序)

4

1 回答 1

0

MSVC 使用“相同的 comdat 折叠”(ICF)。这采用具有相同实现的任何两个方法(或函数)......并为它们使用相同的函数。

gcc 的黄金链接器(显然还有 clang)也可以做到这一点(具有不同程度的攻击性)。

除此之外,您必须手动完成。

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; }
 };

或更少的UB。

于 2021-01-08T05:33:15.247 回答