C++ template class inheritance and name looking up

1 #include <stdio.h>
2
3 template <int N>
4 struct Base {
5     int base[N];
6     Base() {
7         for (int i=0; i<N; ++i)
8             base[i] = i;
9     }
10 };
11
12 int base[1024];
13
14 template <int N>
15 struct Foo : public Base<N> {
16     void dump () {
17         for (int i=0; i<N; ++i)
18             printf ("%d ", base[i]);
19         printf ("\n");
20     }
21 };
22
23 int main (int argc, char **argv) {
24     Foo<10> foo;
25     foo.dump ();
26 }

The test CPP program gives different with SunStudio CC and g++.

g++:          0 0 0 0 0 0 0 0 0 0
sunstudio CC: 0 1 2 3 4 5 6 7 8 9

And, if we comment out line #12, i.e., the definition of ::base[], g++ would complain:

test.cpp: In member function `void Foo<N>::dump()':
test.cpp:18: error: `base' undeclared (first use this function)

It's a bug of g++? Actually, no, it's the correct behavior. Refer to the release note of gcc 3.4.

> In a template definition, unqualified names will no longer find
> members of a dependent base (as specified by [temp.dep]/3 in
> the C++ standard).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha