Usage of typename

What is wrong with the following code?

The issue is very simple but hard to notice. If you try to compile this, you will get the following errors:

    main.cpp:24:5: error: need 'typename' before 'OuterStruct<T2>::InnerStruct' because 'OuterStruct<T2>' is a dependent scope
    OuterStruct<T2>::InnerStruct mUsingInner;
    ^
    main.cpp: In function 'int main(int, char**)':
    main.cpp:34:13: error: 'struct InnerStruct_Wrapper<int>' has no member named 'mUsingInner'
    wrapper.mUsingInner = innerStrct;

The Issue

At least it straight away tells you something is wrong with InnerStruct_Wrapper. Here’s what is happening:

The Fix

The only way here is to help the compiler by telling it beforehand that is going to be a class or struct type. The way to tell the compiler that something like this is supposed to be a type name is to throw in the keyword “typename”. The “typename” keyword has to be used everytime you want to tell the compiler that it should expect a Type in its place.

One place where this is used quite a lot is when templates have to implement iterators.

Full Code

The full sample code, along with the fix is provided on Stacked-Crooked.

comments powered by Disqus