c++ - 为什么调用模板成员函数会出错?

标签 c++ templates compiler-errors

template <class T>
class Test{

public:
  Test(T){ }

  template <class U>
  U to() const{ return U(0); }
};


template <class Real>
class Base{

  typedef Test<Real> TST;

protected:
  Base(const TST& t){

    _i = t.to<int>();  // <- but this gives error
  }

  int _i;
};


template <class Real, class T> class Child;

template <class Real>
class Child<Real, int> : public Base<Real>{

  typedef Base<Real> F;
  typedef Test<Real> TST;

public:
  Child() : F(TST(23.0)){ }
};



int main(int argc, char* argv[]){

  Child<double, int> rw;

  Test<double> t1(3.3);
  int i = t1.to<int>();   // <- this works

  return 0;
}

在主要工作中调用to,但我不明白为什么在Base()中调用时它不起作用。我得到的错误是:

t1.cpp: In constructor ‘Base<Real>::Base(const TST&)’:
t1.cpp:20:15: error: expected primary-expression before ‘int’
t1.cpp:20:15: error: expected ‘;’ before ‘int’

最佳答案

因为t类型为Test<Real>哪里Real是一个模板参数,所以 t 的类型实际上是一个依赖类型。你需要让编译器知道to是一个模板函数,使用:

_i = t.template to<int>();

否则您可能会尝试使用 operator<关于 t 的成员叫to (导致一些错误),这是编译器假设的,除非您将其标记为 template 。当从 main 调用电话时,类型 t1Test<double>它不依赖于任何模板参数,因此编译器可以自行计算出它的模板函数。

关于c++ - 为什么调用模板成员函数会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871614/

相关文章:

c++ - 围绕变量 `f` 尝试计算斐波那契 (n) 的堆栈损坏

c++ - 像 iostream 这样的大型包含文件是否有效? (C++)

php - 仅在 Woocommerce 商店页面添加 DIV

c++ - 用于检测模板函数的 Sfinae 类型特征不适用于 std::forward

c++ - 什么时候需要在模板特化的第二个 <> 中指定类型?

scala - 是什么在模式保护中导致匹配元组列表的类型错误

c++ - 无效密文异常

c++ - 如何在截取的屏幕截图上绘制鼠标光标?

compiler-errors - 由于 glib 错误,无法处理 gobject-introspection

c# - 迭代器变量超出 C# 范围