与其他模板方法继承 C++ 模板类
c++ template class inheritance with other template methods
我正在努力解决编译问题。给定一个使用 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
(或除非已将其建立为模板名称),否则不是当前实例化成员的依赖名称不被视为模板名称。
有关更多详细信息:我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象