在派生类中使用基类的别名模板



我在基类中基于别名模板声明别名模板时遇到了一个(可能是语法上的)问题。我找到了3个工作解决方案,但第四个不工作,这是我更喜欢的一个,但它不编译…

我真的不知道是什么问题。此外,我用gcc 4.8.3std=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的分配器,BaseDerived两个类都有一个DummyContainer的实例,以int为模板。double.

别名模板考虑了分配器,以便在更复杂的实现上下文中更容易使用。

Base::ContainerType是模板依赖(即模板参数T_Allocator)类型。

因此,您需要同时使用typenametemplate关键字
using BaseClass = Base<_Allocator>;
template <typename T>
using ContainerType = typename BaseClass::template ContainerType<T>;
//                    ^^^^^^^^^           ^^^^^^^^

现场演示

最新更新