How do I use extern template w/ template specialization?

http://ideone.com/wGztUW
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
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

struct Outer
{
	template<typename T>
	void go()
	{
		std::cout << Test<T>::f() << std::endl;
	}
private:
	template<typename T>
	struct Test
	{
		static int f();
	};
};

extern template struct Outer::Test<int>;
extern template struct Outer::Test<double>;

int main()
{
	Outer o;
	o.go<int>();
	o.go<double>();
}

template<>
int Outer::Test<int>::f()
{
	return 1;
}
template<>
int Outer::Test<double>::f()
{
	return 2;
}
I have tried several variants on this code to no avail. Outer is in a header, along with the extern template statements, and the specializations after main are in their own cpp file. Main is in a different cpp file.

What do have to do to make this work? I cannot bring the definitions of f() into the header, and they will be different for different template parameters. Ideally, I want Test to remain a private member of Outer, though this can change if it's the only option.
Last edited on
OK, apparently it wasn't so hard: http://ideone.com/opOr15
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
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

struct Outer
{
	template<typename T>
	void go()
	{
		std::cout << Test<T>::f() << std::endl;
	}
private:
	template<typename T>
	struct Test
	{
		static int f();
	};
};

template<> int Outer::Test<int>::f();
template<> int Outer::Test<double>::f();
extern template struct Outer::Test<int>;
extern template struct Outer::Test<double>;

int main()
{
	Outer o;
	o.go<int>();
	o.go<double>();
}

template<>
int Outer::Test<int>::f()
{
	return 1;
}
template<>
int Outer::Test<double>::f()
{
	return 2;
}
I just had a hard time understanding this SO answer: http://stackoverflow.com/a/5356346/1959975

I have some tedious work ahead. I have 12 possible instantiations I need to cover and two functions in my real code, so that's going to be 36 lines of just declarations... EDIT: Wasn't so hard :)
Last edited on
Topic archived. No new replies allowed.