c++ - .template (dot-template) 构造用法

标签 c++ templates

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

我遇到了一段奇怪的代码:

#include <iostream>

template <int N>
struct Collection {
  int data[N];

  Collection() {
    for(int i = 0; i < N; ++i) {
      data[i] = 0;
    }
  };

  void SetValue(int v) {
    for(int i = 0; i < N; ++i) {
      data[i] = v;
    }
  };

  template <int I>
  int GetValue(void) const {
    return data[I];
  };
};

template <int N, int I>
void printElement(Collection<N> const & c) {
  std::cout << c.template GetValue<I>() << std::endl; /// doesn't compile without ".template"
}

int main() {
  Collection<10> myc;
  myc.SetValue(5);
  printElement<10, 2>(myc);
  return 0;
}

printElement 函数中没有 .template 关键字就不会编译。我以前从未见过这个,我不明白需要什么。试图删除它,我得到了很多与模板相关的编译错误。所以我的问题是什么时候使用这种结构?常见吗?

最佳答案

GetValue是从属名称,因此您需要明确告诉编译器 c 后面的内容是一个函数模板,不是一些成员数据。这就是为什么你需要写template关键字来消除歧义。

没有 template关键字,如下

c.GetValue<I>()  //without template keyword

可以解释为:

//GetValue is interpreted as member data, comparing it with I, using < operator
((c.GetValue) < I) > () //attempting to make it a boolean expression

<被解释为小于运算符,并且 >被解释为大于运算符。上面的解释当然是不正确的,因为它没有意义,因此会导致编译错误。

有关更详细的解释,请在此处阅读接受的答案:

关于c++ - .template (dot-template) 构造用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8463368/

相关文章:

c++ - 编译时模板值推导

c++ - HTTP 库对类似 HTTP 的服务器/客户端应用程序有用吗?

c++ - 在 C++ 中将 RGB 转换为 HSL

c++ - 模板模板参数的参数似乎是非模板类型

c++ - 唯一指针: LValue Reference vs RValue Reference function calls

c++ - 为什么十进制浮点运算的提议没有被 C++0x 接受?

c++ - 如果在 C++ 中有多个继承模板,则非法调用非静态成员函数

c++ - 访问模板中的成员: how to check if the template is a pointer or not?

c++ - 具有不同返回类型的成员函数的模板化别名

C++:如何在声明它的模板类主体之外定义枚举类?