.template(点模板)构建用法 [英] .template (dot-template) construction usage

查看:149
本文介绍了.template(点模板)构建用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

I've come across a strange segment of code:

#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;
}

不会编译 .template printElement 功能。我从来没有见过这个,我不明白需要什么。试图删除它,我有很多模板相关的编译错误。所以我的问题是什么时候使用这样的结构?是否常见?

It is not compiled without .template keyword in printElement function. I've never seen this before and I don't understand what is needed for. Trying to remove it, I got a lot of template-related compilation errors. So my question is when such a construction is used? Is it common?

推荐答案

GetValue 是一个依赖名称,因此你需要明确告诉编译器 c 是一个函数 template ,而不是一些成员数据。这是为什么你需要写模板关键字来消除歧义。

GetValue is a dependent name, and so you need to explicitly tell the compiler that what follows c is a function template, not some member data. That is why you need to write template keyword to disambiguate this.

没有 / code>关键字,以下

Without template keyword, the following

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

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

that is, the < is interpreted as less-than operator, and > is interpreted as greater-than operator. The above interpretation is of course incorrect, as it doesn't make sense, and therefore, would result in compilation error.

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

For more detail explanation, read the accepted answer here:

  • Where and why do I have to put the "template" and "typename" keywords?

这篇关于.template(点模板)构建用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆