Tuesday, April 12, 2005

Dependent name look-up

Yay! Learned something new. I came across this in the comp.lang.c++ newsgroups. One of the murkier corners of C++ I must say... Just for redundancy, I'll retype the snippet here...

template < typename T >
class A {
    T n;

template < typename T >
class B : public A< T > { // A partial specialization
    void func() {
      n = 10;

int main()
  B< int > obj;
  return 0;

The problem here is that the compiler does not know anything about 'n' within the function 'func'. Why? This has something to do with the template instantiation. A template class is never instantiated unless there is a particular instantiation object that comes into the picture. So, only when the compiler sees 'B obj;' it creates an instantiation of class B with specialization for an int. But what seemed somewhat queer was that while instantiating class B for int, the compiler would face the public derivation from A. Then why is not class A instantiated for int?! The newsgroups say that in case of template classes the base class is not searched for dependent names' look-up. It also provides a solution for such a scenario.

using A< T >::n;

This statement within class B would resolve the problem.

Its a sea out there!

No comments:

Post a Comment

What I want to say is: