c++ - 什么时候应该在模板函数中使用 typename?

标签 c++ templates c++11

<分区>

根据 this question , typename 应该被添加来告诉编译器 iterator 是一个类型(是否正确?),例如

template <typename T>
void print(vector<T> &v) {
  for (typename vector<T>::const_iterator it=v.begin(); it!=v.end(); ++it)
    cout<<*it<<endl;
}

两个问题:

  1. 什么情况下应该加typename?谁能再举一个例子?

  2. C++11 中的 auto 能否替换所有这些 typename xxx 情况?

最佳答案

  1. 当您引用的类型名称的确切含义取决于模板参数时。
  2. 不是全部,但是很多。 auto 必须能够推断/推导类型。在这样的事情中:

    typename T:foo_t var;
    

例如,它不能。

关于c++ - 什么时候应该在模板函数中使用 typename?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451831/

相关文章:

c++ - 打印奇数

c++ - 这个模板函数是在哪里生成的呢?可以通过 g++ 编译,但不能在 Visual Studio 中编译

c++ - 默认参数,gcc vs clang

algorithm - "find the line that contains the maximum number of points in P"的哈希函数

c++ - 将 std::unique_ptr 类成员标记为 const

c++ - 体素 block 没有渲染正确的 block ?

C++:我无法发现的简单错误! C2146

c++ - 使用矩阵模板库的矩阵乘法(MTL 2)

Swift:将通用的 FloatingPoint 值转换为 Int

C++ 传递带有范围参数的回调