【问题标题】:templated class nested type typename模板类嵌套类型类型名
【发布时间】:2012-10-19 07:59:40
【问题描述】:

我必须将Iter 声明为typename,但没有typedef
然后,我不能在我的template class 声明中使用Iter => 令人沮丧:(
请教我如何使用Iter,否则请解释我为什么C++如此nasty...

template <typename T>
struct MyContainer
{
  typedef  std::vector<T>  Vec;
  typename Vec::iterator   Iter;

  void Fo (typename std::vector<T>::iterator);  //ok
  typename std::vector<T>::iterator Ba();       //ok

  void Foo (Iter);   //error: 'Iter' is not a type
  Iter Bar ();       //error: 'Iter' does not name a type
};                   //(gcc 4.1.2)
  1. 为什么typedef不能用来声明Iter?为什么不呢?
  2. 如何在templateclass内使用Iter? (例如作为函数参数类型)

EDIT
在指令typename Vec::iterator Iter; 中,关键字typename 表示Vec::iterator 是一种类型(即不是静态成员函数/属性)。因此,Iter 没有声明为类型,而是使用类型Vec::iterator 声明为变量。

【问题讨论】:

    标签: c++ templates typedef nested-class typename


    【解决方案1】:
    1. typedef 可以与typename 一起使用。于是就变成了:

      typedef typename vec::iterator Iter;
      
    2. 现在就使用Iter

      template <typename T>
      struct MyContainer
      {
        typedef  std::vector<T>         Vec;
        typedef typename Vec::iterator  Iter;
      
        void Foo (Iter);   //ok
        Iter Bar ();       //ok
      };
      

    【讨论】:

    • 完美 :) 我刚刚在您的回答中添加了代码源解决方案 :-D 谢谢 ;)
    • @olibre 关于您对此答案的编辑(我已回滚):可以通过缩进两次(4 + 4 = 8 个空格)在枚举中使用块引用。不需要任何不寻常的枚举语法...
    • @jogojapan 感谢您的提示/建议:-D
    【解决方案2】:

    只是为了补充上一个答案...

    typename Vec::iterator   Iter;
    

    是一个有效的 C++ 语句,它声明的不是类型而是一个名为 Iter 的变量。

    引入了关键字typename 来指定后面的标识符是一个类型。在解析Vec::iterator 时,编译器无法识别iterator 表示类型,因为它是依赖于模板的名称。它也可以是Vec 中的静态数据成员。

    Officially, what is typename for?

    【讨论】:

    • 是的,typenametypedef 分别声明了变量名变量类型,不是吗?
    • @olibre:你说的不太对。我在答案中添加了解释。
    • +1 感谢您的提醒:iterator 可以是属性或函数...
    【解决方案3】:

    这一行:

    typename Vec::iterator   Iter; 
    

    声明一个名为Iter,类型为Vec::iterator(即vector&lt;T&gt;::iterator)的成员变量,而不是一个类型。

    看看你在这之后做了什么,你可能的意思是:

    typedef  typename Vec::iterator   Iter; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2011-03-26
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多