.template(点模板)构造用法

mko*_*tya 49 c++ templates

可能重复:
我必须在何处以及为何要使用"template"和"typename"关键字?

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Naw*_*waz 61

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

没有template关键字,以下内容

c.GetValue<I>()  //without template keyword
Run Code Online (Sandbox Code Playgroud)

可以解释为:

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

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

有关详细说明,请在此处阅读接受的答案: