在模板中使用 - >以强制使用以下符号

Joh*_*0te 4 c++ templates

从问题:

正确使用这个 - >

答案表明 - >可以使用

...在模板中,为了强制后面的符号依赖于后一种用途,它通常是不可避免的.

这意味着什么是这个用途的好例子是什么意思?在这种情况下,我并不完全"依赖"意味着什么,但这听起来像是一个有用的技巧.

Pub*_*bby 12

发表于其他问题:

template <class T>
struct foo : T {
  void bar() {
    x = 5;       // doesn't work
    this->x = 5; // works - T has a member named x
  }
};
Run Code Online (Sandbox Code Playgroud)

没有this->编译器不知道x是(继承)成员.

与模板代码的使用typenametemplate内部类似:

template <class T, class S>
struct foo : T {
  typedef T::ttype<S>; // doesn't work
  typedef typename T::template ttype<S> footype; // works
};
Run Code Online (Sandbox Code Playgroud)

这是愚蠢的,有点不必要,但你还是要做.

  • @ w00te它使用`template`作为限定符.没有它,编译器会将`<S`视为小于S. (3认同)

Pra*_*ian 5

template <typename T>
struct Base
{
  void foo() {}
};

template <typename T>
struct Derived : Base<T>
{
  void bar()
  {
    // foo();  //foo() is a dependent name, should not call it like this
    // Base<T>::foo(); //This is valid, but prevents dynamic dispatch if foo is virtual
    this->foo(); //use of this-> forces foo to be evaluated as a dependent name
  }
};
Run Code Online (Sandbox Code Playgroud)

有关C++ FAQ的更详细说明