首页 > 解决方案 > 在派生类中使用基类的别名模板

问题描述

在基于基类中的别名模板声明别名模板时,我遇到了一个(可能是语法)问题。我找到了 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,这两个类 -BaseDerived- 都有一个DummyContainer, 模板的实例intdouble.

别名模板将分配器考虑在内,以便在更复杂的实现上下文中更轻松地使用。

标签: c++c++11templatesaliasclass-template

解决方案


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

因此,您需要在此处使用 bothtypenametemplate关键字

using BaseClass = Base<_Allocator>;
template <typename T>
using ContainerType = typename BaseClass::template ContainerType<T>;
//                    ^^^^^^^^^           ^^^^^^^^

现场演示


推荐阅读