Search code examples
c++typename

Shouldn't `typename` only be used in template function or template class?


Shouldn't typename only be used in template function or template class? Why the expresion below is legal?What's the function of typename in the expresion below?

#define DECLARE(T)  using Request = typename T::Request;

I would be grateful for any hint on this question.


Solution

  • This is to allow using such expression in a macro (like mentioned in the original post).

    Macro cannot know if it is used with template type argument or not, but has to work in both. Since typename is required when working with a template, it makes sense to allow it in non-template code (where it can be ignored).

    Your original code serves as the example of such usage (; at the end removed):

    #define DECLARE(T)   using Request = typename T::Request
    

    This macro work in both template and non-template code:

    struct Container { using Request = int; };
    struct A { DECLARE(Container); };
    template<typename T>
    struct B { DECLARE(T); };
    

    Without typename, you would get compilation error for such code:

    B<Container>();