基本类型的C ++模板继承问题 [英] C++ template inheritance issue with base types
问题描述
我有以下代码,无法编译
template<类型名T>
class Base
{
public:
typedef T * TPtr;
void func()
{
}
};
template<类型名T>
class Derived:public Base< T>
{
public:
using Base< Ttr。
using Base< T> func;
TPtr ptr;
};
int main(int c,char * v [])
{
Derived< int> d;
d.func();
}
编译器发出以下命令。
t.cpp:16:error:'TPtr'没有命名类型
t.cpp:16:note:(可能'typename Base< T& :: TPtr')
现在我知道我可以简单地做编译器建议,不能理解为什么
使用Base< Ttr。
无效。
我注释掉 TPtr ptr
然后它编译,证明使用Base< T> :: func; $ c
T> :: TPtr
是所谓的依赖名称,因此您需要在其前面加上 typename
此外,使用
不能使用 typename
,因此您需要使用 typedef
:
typedef typename Base< T> :: TPtr TPtr;问题是编译器不能决定 - 在不知道 T的情况下是什么样子的问题。
$ b < 是! - 在此上下文中是否 TPtr
命名类型或变量/函数。为了避免歧义,除非另有明确说明(因此需要 typename
),否则它总是假定后者。
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?
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
).
这篇关于基本类型的C ++模板继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!