C++11 中依赖类型的模板关键字 [英] Template keyword for dependent types in C++11

查看:27
本文介绍了C++11 中依赖类型的模板关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个更深入的后续:这个问题

考虑以下代码:

template A类{民众:模板const T2* DoSomething() { ... }};模板 B类:公共A<T>{民众:const int* DoSomethingElse() {return this->DoSomething();//编译器需要在这里使用 'template' 关键字://返回 this->template DoSomething();}};

为什么不编译?我知道标准的相关部分是 14.2/4,但我不确定我是否理解为什么这不起作用的具体细节.有人可以分解该部分中的措辞来解释为什么这不起作用吗?另外,你能描述一下(一般)在什么情况下模板关键字可以省略?

请注意,在 C++11 中,以下代码可以编译:

template A类{民众:模板const T2* DoSomething() { ... }};B类{民众:scoped_ptr>变量_;const int* DoSomethingElse() {返回 var_->DoSomething();}};

有什么区别?

解决方案

这是因为 C++ 不是上下文无关的语法.

通常,编译器会查看之前声明的符号来决定标记序列中的尖括号 DoSomething<int> 是关系运算符或模板名称的一部分.由于这是一个模板,尚不知道 A<T> 是否会被特化,编译器不能依赖符号表中的先前声明,需要程序员的帮助.

This is an even more in-depth follow-on to: this question

Consider the following code:

template <typename T>
class A {
 public:
  template <typename T2>
  const T2* DoSomething() { ... }
};

template <typename T>
class B : public A<T> {
 public:
  const int* DoSomethingElse() {
    return this->DoSomething<int>();  // Compiler wants 'template' keyword here:
 // return this->template DoSomething<int>();
  }
};

Why doesn't this compile? I understand that the relevant section of the standard is 14.2/4, but I'm not sure I understand the nuts and bolts of why this doesn't work. Can someone break down the wording in that section to explain why this doesn't work? Additionally, can you describe (generally) under what circumstances the template keyword can be omitted?

Note that in C++11 the following code does compile:

template <typename T>
class A {
 public:
  template <typename T2>
  const T2* DoSomething() { ... }
};

class B {
 public:
  scoped_ptr<A<int>> var_;

  const int* DoSomethingElse() {
    return var_->DoSomething<int>();
  }
};

What's the difference?

解决方案

It's because C++ is not a context-free grammar.

Normally, the compiler looks at previously declared symbols to decide whether the angle brackets in the token sequence DoSomething, <, int, > are relational operators or part of a template name. Since this is a template, and it isn't yet known whether A<T> will be specialized, the compiler cannot rely on prior declarations in the symbol table and needs help from the programmer.

这篇关于C++11 中依赖类型的模板关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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