Constants Defined in Template Classes

Possible duplicate:
GCC problem: using a base class member that depends on template argument

I thought I was familiar with C ++, but apparently not familiar enough.
The problem is when you define a constant in a template class, you can use the constant in new classes that come from this class, but not new template classes that stem from it.

For example, gcc says

test.h: 18: error: "a constant was not declared in this area

when I try to compile this (simplified) header file:

#pragma once template <typename T> class base { public: static const int theconstant = 42; }; class derive1 : public base<size_t> { public: derive1(int arg = theconstant) {} }; template<typename T> class derive2 : public base<T> { public: derive2(int arg = theconstant) {} // this is line 18 }; 

So the problem is that one class, derive1 , compiles fine, but another class derive2 , which is a specialized template, does not. Now, perhaps the gcc error is not clear enough, but I don’t understand why the constructor in derive2 will have a different scope than in derive1 .
In case this matters, this happens during compilation of the header file itself, and not when creating an instance of an object of type derive2<type> .

I also know what needs to be changed to make this compilation, so I am not looking for single-line code snippets as answers. I want to understand why this is happening! I tried searching on the Internet, but apparently I am not using the correct search arguments.

+8
c ++ templates g ++
source share
2 answers

I am sure this will help you understand:

Code that does not compile:

 template<typename T> class derive2 : public base<T> { public: derive2(int arg = theconstant) {} // this is line 18 }; 

And the reason:

 template <> class base<size_t> { public: static const int ha_idonthave_theconstant = 42; }; derive2<size_t> impossible_isnt_it; 

Specialization!!! The compiler on your line 18 cannot be sure that you will not specialize the base <> so that this constant is not present at all.

+2
source share

Try

 template<typename T> class derive2 : public base<T> { public: derive2(int arg = base<T>::theconstant) {} // this is line 18 }; 

Basically you specified an incomplete area for a "constant".

+2
source share

All Articles