基本类型的C ++模板继承问题 [英] C++ template inheritance issue with base types

查看:145
本文介绍了基本类型的C ++模板继承问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,无法编译

  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;

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆