c++ - 错误 : expected primary-expression before ‘>’ : templated function that try to uses a template method of the class for which is templated

标签 c++ templates

<分区>

在使用模板和仿函数(未出现在这个问题中)时,我最终遇到了以下简化的问题。

以下代码(也可用 here )

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

产生一个错误

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

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

还有,附带问题,我应该如何更好地重命名我的问题?

最佳答案

template 内,如果你有一个变量,其类型是你的 template 的函数参数,或者类型是你的函数的类型 template参数,这称为依赖类型。

在你的例子中,evaluator类型 T具有依赖于 template 的类型参数。

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

编译器希望在实际填充 template 之前能够部分理解您的代码实例化中的参数。默认情况下,它假定依赖类型中的所有 都是值。

所以 evaluator是依赖类型,evaluator.isGood假定为一个值,所以 evaluator.isGood<B正在使用 operator<evaluator.isGood和一些未知值 B (它找不到:错误),然后您执行其返回值 >(value)在。 B不是值(而是类型),因此您的代码有误。

你必须告诉编译器 isGood不是一个值,而是一个 template当它在依赖上下文中使用时。

evaluator.template isGood<B>(value)是语法。 template告诉编译器“虽然默认情况下你会假设一个值来了,而不是一个 template 来了”。有涉及使用 typename 的类似规则在 template 内(但是 typename 更早,所以它处于一个更糟糕的位置)来指示否则被假定为值的实际上是一种类型。

在你的main方法,evaluator不是依赖类型,因此不需要帮助。

关于c++ - 错误 : expected primary-expression before ‘>’ : templated function that try to uses a template method of the class for which is templated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947863/

相关文章:

c++ - 为什么 IUnknown 类中的方法声明为 __stdcall

C++:遍历泛型列表

c++ - 如何从反汇编中判断是否使用了函数的内部版本?

c++ - 如何让 C++ 从 lambda 推断模板类型参数?

c++ - boost::mutex 在模板中使用时不起作用

运行时的 C++ 变量类型

c++ - 如何使用 Digest 身份验证下载 Web 资源

c++ - 是否可以在 C++14 中分配和验证 constexpr 结构?

c++ - 具有用户定义类型的自动非类型模板参数

C++ 模板 const char 数组到 int