【问题标题】:.template (dot-template) construction usage [duplicate].template(点模板)构造用法[重复]
【发布时间】:2012-01-17 19:13:05
【问题描述】:

可能重复:
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 关键字就不会编译。我以前从未见过这个,我不明白需要什么。试图删除它,我得到了很多与模板相关的编译错误。所以我的问题是什么时候使用这种结构?常见吗?

【问题讨论】:

  • 只是为了记录,它不是.template(单个点模板结构),而是两个标记,一个点,后跟template 关键字。写c. template GetValue&lt;I&gt; 也是合法的。 template 绑定到成员函数 GetValue,而不是点。
  • 这个问题 - 虽然是重复的 - 很有用。只是搜索模板会带来很多噪音。 “dot-template”短语是我最后找到的。

标签: c++ templates


【解决方案1】:

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

也就是说,&lt; 被解释为小于运算符,&gt; 被解释为大于运算符。上面的解释当然是不正确的,因为它没有意义,因此会导致编译错误。

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

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 2015-09-30
    • 1970-01-01
    • 2011-05-24
    • 2016-04-13
    • 2013-04-21
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多