how to initialize static member of class with template and type of a nested class

Hello everyone :D

Can you help us?

We have this question:

How to initialize a static member of a class with template, which type is related to a nested class?

This code works (without nested class):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;

struct B{
	B(){cout<<"here"<<endl;}
};

template<typename Z>
struct A{
	static B*const b;
	static B*bb(){return new B();}

	A(){cout<<b<<endl;}
};

template<typename Z>
B*const A<Z>::b=A<Z>::bb();

int main(){
	A<int>*a=new A<int>[2];
	delete[]a;
}


The same code with nested class gives us a compiler error (GNU compiler):

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

template<typename Z>
struct A{
	struct B{
		B(){cout<<"here"<<endl;}
	};

	static B*const b;
	static B*bb(){return new B();}

	A(){cout<<b<<endl;}
};

template<typename Z>
//Compiler error:
//need ‘typename’ before ‘A<Z>::B’ because ‘A<Z>’ is a dependent scope
A<Z>::B*const A<Z>::b=A<Z>::bb();

int main(){
	A<int>*a=new A<int>[2];
	delete[]a;
}


Thank you very much for your time and answers.

Best regards,

http://ncomputers.org
We found the answer as we started to file a bug on the GNU compiler website and a user of http://www.stackoverflow.com/ answered our question, when he made us a comment related to do what the compiler says.

Just add the typename keyword.

We didn't knew this usage of the typename keyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;

template<typename Z>
struct A{
	struct B{
		B(){cout<<"here"<<endl;}
	};

	static B*const b;
	static B*bb(){return new B();}

	A(){cout<<b<<endl;}
};

template<typename Z>
typename A<Z>::B*const A<Z>::b=A<Z>::bb();

int main(){
	A<int>*a=new A<int>[2];
	delete[]a;
}


Best regards,

http://ncomputers.org
Topic archived. No new replies allowed.