2
#include<iostream>

template<int n>
class Parent
{
    public:
    static const unsigned int n_parent = 5 + n;
};

template<int n>
class Son : public Parent<n>
{
    public:
    static void foo();
    static const unsigned int n_son = 8 + n;
};

template<int n>
void Son<n>::foo()
{
  std::cout << "n_parent = " << n_parent << std::endl;
  std::cout << "n_son = " << n_son << std::endl;
}

This piece of code will generate error

error: use of undeclared identifier 'n_parent'

I have to specify the template parameter explicitly:

template<int n>
void Son<dim>::foo()
{
  std::cout << "n_parent = " << Son<n>::n_parent << std::endl;
  std::cout << "n_son = " << n_son << std::endl;
}

Why the child template class can't deduce the proper scope of the inherited member implicitly?

George
  • 25
  • 3

1 Answers1

2

The compiler does not resolve the inherited members for template base classes, due to the fact that you may have specializations that do not define the member, and in that case the whole parsing/name resolving business will become quite difficult.

If your member is non-static, then using this->n_parent "assures" the compiler that n_parent is indeed a member of the base class. If the member is static, there is no this pointer (as you mention), so the only choice is to qualify the base class as you do.

Related: Derived template-class access to base-class member-data

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252