开发者

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

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

GCC problem : usi开发者_如何学JAVAng 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜