7

New to modern C++, trying to figure out what's going on here. Following code compiles fine:

template<int base_num>
class Base{
public:
  Base() {}
};


template<int derived_num>
class Derived : public Base<0> { // Integer literal passed to base template
public:
  Derived(): Base() {}
};

Whereas the following:

template<int base_num>
class Base{
public:
  Base() {}
};


template<int derived_num>
class Derived : public Base<derived_num> { // Non-type template parameter passed to base template
public:
  Derived(): Base() {}
};

Fails with:

class ‘Derived<derived_num>’ does not have any field named ‘Base’

I'm speculating that this happens because derived_num itself doesn't count as a "structural type", but unsure. Hoping someone can explain what is going on here and if there is a way to "pass-through" non-type template parameters to a base class template.

Update:

Explicitly defining the template "fixes" this

template<int derived_num>
class Derived : public Base<derived_num> {
public:
  Derived(): Base<derived_num>() {}
};

But becomes very budernsome for more complex base templates and multiple constructors. If it can be avoided I would like to, and I still don't understand why this fix works either.

Update 2:

The problem code fails with GCC and clang, but works on MSVC. Compiler bug? (Who's bugged, GCC/Clang or MSVC?) Invoking an MSVC extension? Very out of my element now, will wait patiently for a standards maven to tell me what's supposed to happen here.

nickelpro
  • 2,537
  • 1
  • 19
  • 25
  • @JeJo I had noticed this when I was developing the test case too. I wasn't confident enough I wasn't just compounding on the original problem or not. Updated the question. – nickelpro Jul 10 '20 at 16:42
  • I don't think so. This has nothing to do with accessing member variables, these classes don't even have member variables. For some reason the compiler is failing to recognize the Base template specialization as the Base class when we "pass-through" the non-type template parameter. But I've got no idea what's really going on here. – nickelpro Jul 10 '20 at 16:52
  • 1
    Possible duplicate of https://stackoverflow.com/q/62556571/2752075 – HolyBlackCat Jul 10 '20 at 17:10
  • 3
    *"Who's bugged, GCC/Clang or MSVC?"* Rule of thumb: if they disagree with each other, it's usually MSVC that's bugged. :P – HolyBlackCat Jul 10 '20 at 17:11
  • @HolyBlackCat You're correct, duplicate. Thank you, I was banging my head against a wall. That error message is terrible. – nickelpro Jul 10 '20 at 17:11

0 Answers0