Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template inheritance issue with base types

I have the following code and it fails to compile

template < typename T >
class Base
{
public:

    typedef T * TPtr;

    void func()
    {
    }
};

template < typename T >
class Derived : public Base< T >
{
public:
    using Base< T >::TPtr;
    using Base< T >::func;

    TPtr ptr;
};

int main( int c, char *v[] )
{
    Derived< int > d;
    d.func();
}

The compiler issues the following.

t.cpp:16: error: 'TPtr' does not name a type
t.cpp:16: note: (perhaps 'typename Base<T>::TPtr' was intended)

Now I know I could simply do as the compiler is suggesting but I can't understand why the

    using Base< T >::TPtr;

doesn't work.

If I comment out the "TPtr ptr" line then it compiles, proving that the "using Base< T >::func;" statement works.

Any ideas?

like image 257
ScaryAardvark Avatar asked Feb 15 '26 05:02

ScaryAardvark


1 Answers

Base< T >::TPtr is a so-called dependent name so you need to prefix it with typename to make the declaration work.

Additionally, using doesn’t work with typename so you need to use a typedef instead:

typedef typename Base<T>::TPtr TPtr;

The issue is that the compiler can’t decide – without knowing what T is! – whether TPtr in this context names a type or a variable/function. To avoid ambiguities, it always assumes the latter, unless explicitly told otherwise (hence the need for typename).

like image 87
Konrad Rudolph Avatar answered Feb 16 '26 18:02

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!