2

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

I want to create a template which takes a type T and a parameter N as arguments and 'gives' a pointer of Nth grade for T(eg. if T is int and N is 2 it should give int**)

My code so far is:

template<class T,int N>
struct ptr
{
  typedef ptr<T*,N-1>::t t;
};

template<class T>
struct ptr<T,0>
{
  typedef T t;
};

int main()
{
  ptr<int,3>::t a; //a should be int***
}

But it gives me this compiler error:

source.cpp:6:11: error: need 'typename' before 'ptr<T*, (N - 1)>::t' because 'ptr<T*, (N - 1)>' is a dependent scope

What does this mean and how can it be fixed(if its possible in C++)?

Community
  • 1
  • 1
lazy_banana
  • 450
  • 5
  • 10

2 Answers2

3

The error means that ptr<T*, (N - 1)>::t is a dependent name.

The meaning of t used in a template definition depends upon the template parameters, so the compiler cannot automatically determine that t is a type and not an object.

To correct the error, you have to give the compiler a hint, i.e. to do literally what the message suggests: prefix it with typename

typedef typename ptr<T*,N-1>::t t;
Andriy
  • 8,486
  • 3
  • 27
  • 51
2
template<class T,int N>
struct ptr
{
  typedef typename ptr<T*,N-1>::t t;
};

template<class T>
struct ptr<T,0>
{
  typedef T t;
};

int main()
{
  ptr<int,3>::t a; //a should be int***
}

Compiler tells that t is dependent name, so use typename before ptr<T*, (N - 1)>::t

ForEveR
  • 55,233
  • 2
  • 119
  • 133