错误:'>'之前的预期primary-expression:试图使用模板化类的模板方法的模板化函数

Ant*_*nio 4 c++ templates

在玩模板和仿函数(这个问题中没有)时,我最终遇到了以下简化问题.

以下代码(此处也可用)

class A {
    public:
    template <class T> 
      bool isGood(int in) const {
      const T f;
      return in < f.value();
      }

};

class B {
    public:
    int value() const {return 10;}
};

template <class T>
bool tryEvaluator(T& evaluator, int value) {
    return evaluator.isGood<B>(value);
    }


int main( int argc, const char* argv[] ) {
  const A evaluator;
  evaluator.isGood<B>(20); //Seemingly no problem here
  tryEvaluator(evaluator,20);
  return 0;
  }
Run Code Online (Sandbox Code Playgroud)

生成错误

main.cpp:18:34: error: expected primary-expression before ‘>’ token
         return evaluator.isGood<B>(value);
                                  ^
Run Code Online (Sandbox Code Playgroud)

是否可以执行我想要做的事情?我是否需要添加一些关键字?

而且,附带问题,我该如何更好地重命名我的问题?

Yak*_*ont 9

在a中template,如果您有一个类型是template参数函数的变量,或者类型是template参数函数的类型,则称为依赖类型.

在您的情况下,evaluator类型T的类型取决于template参数.

使用依赖类型或该类型的变量时,需要为编译器提供一些额外的帮助.

编译器希望能够template在实例中将参数实际填充到其中之前部分理解您的代码.默认情况下,它假定一切都一个依赖型是一种价值.

因此evaluator是依赖类型,并且evaluator.isGood假定它是一个值,因此evaluator.isGood<B使用operator<on evaluator.isGood和一些未知值B(它找不到:error),然后返回值>(value). B不是一个值(而是一个类型),所以你的代码是错误的.

您必须告诉编译器isGood不是值,而是template在依赖的上下文中使用它.

evaluator.template isGood<B>(value)是语法.该template告诉编译器"而默认情况下,你认为值的到来,而不是template来了".有一些类似的规则涉及typename在a 中使用template(但是typename更早,因此它在一个更古怪的地方)以指示否则将被假定为值实际上是一种类型.

在您的main方法中,evaluator它不是依赖类型,因此它不需要帮助.