与其他模板方法继承 C++ 模板类

c++ template class inheritance with other template methods

本文关键字:C++ 继承 其他 模板方法      更新时间:2023-10-16

我正在努力解决编译问题。给定一个使用 T 模板化的基类,其中包含一个使用 U 模板化的方法,我无法从派生类调用该方法。以下示例重现了我的问题:

#include <iostream>
#include <vector>
template <class T>
class Base
{
protected:
  template <class U>
  std::vector<U> baseMethod() const
  {
    return std::vector<U>(42);
  }
};
template <class T>
class Derived : public Base<T>
{
public:
  std::vector<int> derivedMethod() const
  {
    return baseMethod<int>();
  }
};
int main ()
{
  Derived<double> d;
  std::vector<int> res = d.derivedMethod();
  return 0;
}

编译器结果:

t.cc:21:12: error: ‘baseMethod’ was not declared in this scope
t.cc:21:23: error: expected primary-expression before ‘int’
t.cc:21:23: error: expected ‘;’ before ‘int’
t.cc:21:26: error: expected unqualified-id before ‘>’ token

您应该添加 template 关键字以将baseMethod视为依赖模板名称:

std::vector<int> derivedMethod() const
{
  return this->template baseMethod<int>();
}

在模板定义中,除非使用消除歧义关键字 template(或除非已将其建立为模板名称),否则不是当前实例化成员的依赖名称不被视为模板名称。

有关更多详细信息:我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?