Templates, nested classes and static members

Hello,

How do I initialise the static member variable in a template class that has type equal to a nested class?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using namespace std;

template <typename T>
class M {    //This is a memory manager
  public:
  T x;
  M(T& xx) : x(xx) {}
};

template <typename T2>
class C {      //This is a generic container type
protected:
  class N {       //This is a node in the container
  public:
    T2 y;
  };
  static M<N> my_static;  //We want one memory manager for all instances
};

template <typename T2>
C<T2>::M< C<T2>::N > C<T2>::my_static(1);  //Line 21: initialisation

int main() {
  C<int> c;
}


The error (g++ 4.1.2) is

test.cpp:21: error: expected constructor, destructor, or type conversion before '<' token

I get the same error if I replace line 21 with
1
2
template <typename T2>
C<T2>::M<N> C<T2>::my_static(1);


Since M is not a member class, I tried
1
2
template <typename T2>
M< C<T2>::N > C<T2>::my_static(1);

which gave the error
test.cpp:21: error: type/value mismatch at argument 1 in template parameter list for 'template<class T> class M'
test.cpp:21: error: expected a type, got 'C<T2>::N'
test.cpp:21: error: invalid type in declaration before '(' token
test.cpp:21: error: conflicting declaration 'int C<T2>::my_static'
test.cpp:17: error: 'C<T2>::my_static' has a previous declaration as 'M<C<T2>::N> C<T2>::my_static'
test.cpp:21: error: declaration of 'M<C<T2>::N> C<T2>::my_static' outside of class is not definition


This is a boiled down version of an STL type container that I'm writing: C is the container; the data is stored in objects of type N (nodes); the class M handles allocation etc. for the nodes.

This one has had me stumped for many hours.

Cheers,

David.
Last edited on
Try this:
1
2
template <typename T2>
M< typename C<T2>::N > C<T2>::my_static(1);  //Line 21: initialisation 


However, I don't think you will get one memory manager for all instances of the template. Why don't you declare my_static globally outside the template?
Thanks, that works perfectly.

I checked, and the memory manager is constructed once per template type, that is,
1
2
3
C<int> c1;
C<int> c2;
C<double> c3;

results in exactly two calls to the constructor of M.

I guess my rationale for using a static member for the memory manager is that I don't want access to the manager outside my class. I don't know if that is justified.

Thanks again---I really appreciate it.

-David.
If that's what you wanted, it's perfect. But I thought you wanted the same memory manager for the <int> and <double> instances.
Topic archived. No new replies allowed.