jeudi 10 mars 2022

What is causing this baffling compiler error with templates and inheritance? [duplicate]

It took quite a while to distill this down to a manageable size, but here's the code:

template<typename T = uint8_t> struct ArrayRef {
  T* data;
  size_t size;
  size_t capacity;

  ArrayRef<T>(T* d, size_t c, size_t size) : data(d), size(size), capacity(c) {}

  void Add(T* buffer, size_t size) { }
};

struct ByteArray : ArrayRef<uint8_t> {
  ByteArray(uint8_t* d, size_t c, size_t size) : ArrayRef<uint8_t>(d,c,size) {}

  // If this function is removed, the test code can find the inherited Add function
  template <typename T> void Add(T& item) { }
};

void Test() {
  uint8_t ibuf[20];
  ByteArray ba(ibuf, 20, 0);
  uint8_t buf[5];
  ba.Add(buf, sizeof(buf));

If this code is compiled as is (g++), I get the compiler error:

error: no matching function for call to 'ByteArray::Add(uint8_t [5], unsigned int)

But, as noted in the code, when the one function is removed, the code compiles fine and the Add function in the base class is found correctly. What exactly is going on here?

Aucun commentaire:

Enregistrer un commentaire