【发布时间】:2021-11-15 15:34:50
【问题描述】:
在基于基类中的别名模板声明别名模板时,我遇到了一个(可能是语法)问题。我找到了 3 个可行的解决方案,但第 4 个不起作用,这是我更喜欢的一个,但它无法编译...
我真的不知道问题出在哪里。此外,我用gcc 4.8.3 和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;
请看下面的代码,欢迎提出想法和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 的分配器,两个类 - Base 和 Derived - 都有一个 DummyContainer 的实例,模板分别为 int。 double.
别名模板将分配器考虑在内,以便在更复杂的实现上下文中更轻松地使用。
【问题讨论】:
标签: c++ c++11 templates alias class-template