livefree75
livefree75

Reputation: 763

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

Say I have this (stuck with 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;
}

I want to typedef FooMap<T,S>::Iterator and FooMap<T,S>::Entry but if I try this:

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

I get "error: ‘T’ was not declared in this scope". If I try putting template parameters on it:

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

I get "error: expected unqualified-id before ‘template’".
I have resorted to using a #define:

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

This seemed to work (although it doesn't work on Online C++ Compiler).

Seems kind of hackish though.

Any ideas?

Upvotes: 0

Views: 75

Answers (2)

JHBonarius
JHBonarius

Reputation: 11261

C++11 has `using for this :)

When I tried on C++03, I got the error "need typename before FiniteMap as it is a dependent scope...

Thus:

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;
}

On GodBolt

Upvotes: 2

Yunnosch
Yunnosch

Reputation: 26703

With

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

compiler complains about T (and probably S) not being declared - and I have to agree.
If you want to keep T abstract, then you are stuck with using the parameterised template.

But I think you actually want to typedef a "short" for the specific case of T=Foo and S=5.
That can be done this way

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

Upvotes: 1

Related Questions