【问题标题】:Use alias template from base class in derived class [duplicate]在派生类中使用基类的别名模板[重复]
【发布时间】:2021-11-15 15:34:50
【问题描述】:

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

我真的不知道问题出在哪里。此外,我用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;
     

请看下面的代码,欢迎提出想法和cmets:

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++11 templates alias class-template


    【解决方案1】:

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

    因此,您需要在此处同时使用 typenametemplate 关键字

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

    Live Demo

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2020-09-03
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多