0

You see, i like structs, so i put some structs inside structs and try to use these nested structs in a class template to declare some variables. The only problem is: it just doesn't seem to work as expected. This is my minimal example code:

#include "stdafx.h"
#include <iostream>

struct T1
{
    struct NESTED
    {
        int var1 = 12345;
    };
};

struct T2
{
    struct NESTED
    {
        float var1 = 67890;
    };
};


template <typename T > class Proletarian
{
public:
    T * t;                                       //works
  //T::NESTED * tn;        ****** doesn't work! *******
    Proletarian<typename T>()
    {
        T::NESTED * tNested = new T::NESTED;     //works
        std::cout << tNested->var1;
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    Proletarian<T1> t1 = Proletarian<T1>();
    Proletarian<T2> t2 = Proletarian<T2>();

    return 0;
}

I use Visual Studio 2013, Intellisense is ok with my code, but it just won't compile with these two errors:

[Line 20 Column 1] error C2143: syntax error : missing ';' before '*'

[Line 20 Column 1] error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

I'm not that good at C++, so probably don't quite understand how templates work and why this actually happens.

Noam M
  • 3,156
  • 5
  • 26
  • 41
Grabz
  • 3
  • 1
  • 1
    You need to specify `typename` in a few places. [see it live](http://ideone.com/e4ZNFM). See this question: ["Where and why do I have to put the “template” and “typename” keywords?"](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords). In particular, [this *stellar* answer](http://stackoverflow.com/a/613132/1322972) from Johannes. – WhozCraig Jun 01 '15 at 05:15

1 Answers1

1

When the compiler first passes over Proletarian - before it sees an instantiation for a specific type T - it need help to know that T::NESTED will refer to some type, which you can give it using typename as follows:

template <typename T>
class Proletarian
{
  public:
    typename T::NESTED* tn;
    Proletarian<T>()
    {
        typename T::NESTED* tNested = new typename T::NESTED;
        std::cout << tNested->var1;
    }
};
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252