dimanche 1 mars 2020

c++ - using Enum as template type and can't access parent class fields from within inheriting class

consider the following code

#include <iostream>

template <size_t N>
struct A {
  int arr[N];
};


template <typename ENUM> 
struct B : public A<ENUM::Size> {
  int foo() { return sizeof(*this); }
};

struct E {
  enum E_ {a, b, c, Size};
};

int main() {
  B<E> b;
  std::cerr << b.foo() << "\n";
}

so far everything compiles just fine, and prints 12. but when i change foo implementation:

int foo() { return arr[0]; } // should inherit arr from parent class A

I'm getting a compilation error:

error: `arr` was not declared in this scope
   int foo() { return i; }

what am I missing? can I make it work?

(obviously, when I change B definition to something silly:

struct B : public A<17> {
  int foo() { return arr[2]; }
};

everything compiles just fine)

what's even more surprising to me is the fact that if I add this line to main():

b.arr[0] = 3;

everything still compiles just fine, so it seems I just can't access A fields from within B

thanks

Aucun commentaire:

Enregistrer un commentaire