Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template class inheriting another template class with a template-specified input type [duplicate]

Possible Duplicates:
GCC problem : using a member of a base class that depends on a template argument
Why does GCC need extra declarations in templates when VS does not?
Why doesn’t a derived template class have access to a base template class
iphone compiler inherited templated base classes with passed through type not being expanded in time (just look)

Sorry for the confusing title, best I could come up with.

Here's some code to illustrate my problem...

A base template class:

template<class T> class TestBase
{
public:
   int someInt;
};


Attempting to subclass TestBase with another template class...

This gets "someInt was not declared in this scope" at compile time:

template<class X> class TestSub : public TestBase<X>
{
   void testf()
   {
       someInt = 0; //Error: "someInt was not declared in this scope"
   }
};



B) This works fine (the difference being that I specify TestBase's template input explicitly)

template<class X> class TestSub : public TestBase<string>
{
   void testf()
   {
       someInt = 0;
   }
};



Why does TestSub from (A) not inherit someInt correctly as it does in (B)?

Thanks in advance.

like image 255
Josh Rosen Avatar asked Jul 19 '10 00:07

Josh Rosen


1 Answers

Because TestBase could be specialized on X whatever X ends up being. Therefore you need to let the compile know someInt is a dependent value by fully qualifying it. Instead of

     someInt = 0

say rather

     TestBase<X>::someInt = 0

You could also use

     this->someInt = 0

The point is the compiler will not assume a name is dependent on a template parameter it must know it is before it defers that check to instantiation time. For an experiment see what happens when you introduce a global someInt.

like image 83
Logan Capaldo Avatar answered Oct 06 '22 13:10

Logan Capaldo