c++ - 在派生类中使用基类的别名模板
问题描述
在基于基类中的别名模板声明别名模板时,我遇到了一个(可能是语法)问题。我找到了 3 个可行的解决方案,但第 4 个不起作用,这是我更喜欢的解决方案,但它无法编译...
我真的不知道问题是什么。gcc 4.8.3
此外,我用and编译,std=c++11
我得到了这个:
g++ -Wall -pedantic -std=c++11 main.cpp -o out
main.cpp:43:31: error: expected type-specifier
using ContainerType = BaseClass::ContainerType<T>;
^
main.cpp:46:9: error: ‘ContainerType’ does not name a type
ContainerType<double> double_container;
请看下面的代码,欢迎提出想法和意见:
template <typename T>
class DummyAllocator
{
public:
static T dummy_allocate() { return (T)0; }
};
template <typename T, typename _Allocator = DummyAllocator<T> >
class DummyContainer
{
public:
DummyContainer() { _Allocator::dummy_allocate(); }
};
template <typename _Allocator>
class Base {
public:
template <typename T>
using ContainerType = DummyContainer<T, _Allocator>;
private:
ContainerType<int> int_container;
};
template <typename _Allocator>
class Derived : public Base<_Allocator>
{
public:
// (1) This works!
//template <typename T>
//using ContainerType = DummyContainer<T, _Allocator>;
// (2) This works!
//template <typename T>
//using ContainerType = Base<_Allocator>::ContainerType<T>;
// (3) This works!
//typedef _Allocator Allocator;
//template <typename T>
//using ContainerType = Base<Allocator>::ContainerType<T>;
// (4) This one doesn't compile!
using BaseClass = Base<_Allocator>;
template <typename T>
using ContainerType = BaseClass::ContainerType<T>;
private:
ContainerType<double> double_container;
};
int main(int, const char**)
{
Base<DummyAllocator<int> > base;
Derived<DummyAllocator<int> > derived;
return 0;
}
DummyAllocator
作为 的分配器DummyContainer
,这两个类 -Base
和Derived
- 都有一个DummyContainer
, 模板的实例int
。double
.
别名模板将分配器考虑在内,以便在更复杂的实现上下文中更轻松地使用。
解决方案
这Base::ContainerType
是一个模板依赖(即模板参数T
和_Allocator
)类型。
因此,您需要在此处使用 bothtypename
和template
关键字
using BaseClass = Base<_Allocator>;
template <typename T>
using ContainerType = typename BaseClass::template ContainerType<T>;
// ^^^^^^^^^ ^^^^^^^^
推荐阅读
- python - 使用 pop 方法删除列表中的重复元素
- java - 如果一个方法在一个类中是唯一的,那么抽象类怎么写?
- d3.js - d3.js 强制图形处理 10.000 个数据条目
- javascript - 如何使用 JavaScript 在点击时隐藏 iframe
- firebase - Firebase 分析未显示
- java - 如何在 Java 中说“两个参数必须具有相同的类型”?
- amazon-quicksight - 不显示 Quick Sight 数据
- php - 与 SQL Server 2008 的 PHP 连接
- flutter - 如何在启动谷歌地图网址时应用优化以优化路线?
- bash - 远程服务器上的 Shell 脚本终止 ssh 会话