BillyJean
BillyJean

Reputation: 1587

class of typedefs

I have seen the following piece of code at work

typedef int         real_type;
typedef vector<int> vector_type;


template <class ASD> class program_class
{
  public:
    typename ASD::vector_type member_func();
};


template <typename ASD> typename ASD::real_type program_class<ASD>::member_func()
{
    typedef typename ASD::real_type      R;
    typedef typename ASD::vector_type    V;

    return 123;
}

Conceptually, I don't understand how the return-type can be stated like this: typename ASD::real_type. In principle this requires that the type we instantiate ASD with is a class of typedefs, right?

Can I see an example of how this is accomplished?

Upvotes: 0

Views: 71

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

The global vector_type is in the global namespace. If you use the scope operator :: the scope is changed to that left of the scope operator, in the case of the templates the scope is ASD and no longer the global scope.

That means, as you noticed, that the ASD class (whatever that is) must have its own vector_type and real_type defined inside it, or the compiler will give you an error.


Example:

typedef int real_type;  // The global type alias
...

struct Foo
{
    typedef long real_type;  // The local type alias
    ...
};

program_class<Foo> my_program_object;

Now inside the program_class the real_type will be Foo::real_type and not the global ::real_type.

And as you can see in my example, you can use different base types, as the two type aliases are completely separate from each other.

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137810

Correct. Processing the declaration with such a return type causes instantiation of whatever, if any, class template ASD refers to.

If a member declaration in ASD has an error, then the compiler will complain that nested instantiation of ASD failed while instantiating program_class< ASD >.

Upvotes: 1

Related Questions