bryan sammon
bryan sammon

Reputation: 7441

typedef of a template with a template type as its parameter

Im having a problem with a typedef below, I can seem to get it right:

template <typename T>
  struct myclass1 {
  static const int member1 = T::GetSomeInt();
};

template <int I>
struct myclass2 {
  typedef myclass1< myclass2<I> > anotherclass;
  static int GetSomeInt();
};

anotherclass MyObj1; // ERROR here not instantiating the class

When I try and initialize a anotherclass object, it gives me an error.

Any idea what I am doing wrong? There seems to be a problem with my typedef.

Any help is appreciated, Thanks Bryan

Upvotes: 0

Views: 112

Answers (2)

Lily Ballard
Lily Ballard

Reputation: 185831

You're referring to anotherclass directly. That name doesn't exist at that scope. You need to declare your variable as

myclass2<some_int>::anotherclass MyObj1;

where some_int is whatever integer value you want to parameterize myclass2 with.

I think you'll also need to mark myclass2<I>::GetSomeInt() as being constexpr so it can be used in the initializer of myclass1<T>::member1.

With those tweaks, the following code compiles just fine:

#include <iostream>

template<typename T>
struct myclass1 {
    static const int member1 = T::GetSomeInt();
};

template<int I>
struct myclass2 {
    typedef myclass1<myclass2<I>> anotherclass;
    constexpr static int GetSomeInt() { return I; };
};

int main(int argc, char *argv[]) {
    myclass2<3>::anotherclass obj;
    std::cout << obj.member1 << std::endl;
}

Note, this requires C++11 for constexpr. If you want C++03 then I don't think your myclass1<T>::member1 is legal.

Upvotes: 3

vvnraman
vvnraman

Reputation: 1343

You are creating a typedef using myclass1 and passing in a templatised class as the parameter. Hence you need use template template parameters. This means that the declaration of myclass1 should be changed to to tell the compiler that T in template <typename T> is itself a template class.

See if changing the following code

template <typename T>
  struct myclass1 {
  static const int member1 = T::GetSomeInt();
};

to this fixes the problem:

template < template <typename BasicType> class T>
  struct myclass1 {
  static const int member1 = T::GetSomeInt();
};

Upvotes: 0

Related Questions