参数化类的别名(或类型定义)内部类

Aliasing (or typedef'ing) inner class of parameterized class

本文关键字:类型 定义 内部类 别名 参数      更新时间:2023-10-16

假设我有这个(使用C++03(。

template <class T, int S>
class FiniteMap
{
public:
class Iterator {};
class Entry {};
};
class Foo {};
template <class T, int S>
class FooMap : public FiniteMap<T,S>
{
public:
void bar()
{
FooMap<T,S>::Iterator iter;
FooMap<T,S>::Entry    entry;
}
};
int main()
{
return 0;
}

我想typedefFooMap<T,S>::IteratorFooMap<T,S>::Entry,但如果我尝试这个:

typedef FooMap<T,S>::Iterator FooIterator;

我得到"错误:未在此范围中声明'T'"。如果我试着把模板参数放在上面:

typedef
template <class T, int S>
FooMap<T,S>::Iterator FooIterator;

我得到"错误:在'template'之前应为非限定id">
我使用了#define:

#define FooIterator typename FooMap<T,S>::Iterator

这似乎是有效的(尽管它不适用于在线C++编译器(。

看起来有点生气。

有什么想法吗?

C++11具有`using for this:(

当我在C++03上尝试时,我得到了错误"在FiniteMap之前需要typename,因为它是一个依赖范围…

因此:

template <class T, int S>
class FiniteMap {
public:
class Iterator {};
class Entry {};
};
class Foo {};
template <class T, int S>
class FooMap : public FiniteMap<T, S> {
public:
typedef typename FiniteMap<T, S>::Iterator FooIterator;
typedef typename FiniteMap<T, S>::Entry FooEntry;
void bar()
{
FooIterator iter;
FooEntry    entry;
}
};
int main()
{
FooMap<int, 3> test;
return 0;
}

GodBolt

使用

typedef FooMap<T,S>::Iterator FooIterator;

编译器抱怨T(可能还有S(并没有被声明——我不得不同意
如果你想保持T的抽象性,那么你必须使用参数化模板。

但我认为你实际上想为T=Foo和S=5的特定情况键入一个"short"。
这可以通过来完成

/* ... start of your file */
class Foo {};
typedef FooMap<Foo,5>::Iterator FooIterator;
int main()
{
}