That is sad but true: you cannot explicitly specialize a class template unless its enclosing class templates are also explicitly specialized. For more information you may read
Below I've specialized MyClass first and everything got done.
#include <iostream>
using namespace std;
template<typename T1, typename T2> class MyClass
{
public:
template<int num> static int DoSomething();
};
template<typename T1, typename T2> template<int num> int MyClass<T1, T2>::DoSomething()
{
cout << "This is the common method" << endl;
cout << "sizeof(T1) = " << sizeof(T1) << endl;
cout << "sizeof(T2) = " << sizeof(T2) << endl;
return num;
}
template<> template<> int MyClass<char, int>::DoSomething<0>()
{
cout << "This is ZERO!!!" << endl;
cout << "sizeof(T1) = " << sizeof(char) << endl;
cout << "sizeof(T2) = " << sizeof(int) << endl;
return 0;
}
int main() {
MyClass<char, int> m;
m.DoSomething<2>();
m.DoSomething<0>();
return 0;
}
Output:
This is the common method
sizeof(T1) = 1
sizeof(T2) = 4
This is ZERO!!!
sizeof(T1) = 1
sizeof(T2) = 4
EUREKA! This works well on MSVCPP 10.
#include <iostream>
using namespace std;
template<typename T1, typename T2> class MyClass
{
public:
template<int num> static int DoSomething();
template<> static int DoSomething<0>() {
cout << "This is ZERO!!!" << endl;
cout << "sizeof(T1) = " << sizeof(T1) << endl;
cout << "sizeof(T2) = " << sizeof(T2) << endl;
return 0;
}
};
template<typename T1, typename T2> template<int num> int MyClass<T1, T2>::DoSomething()
{
cout << "This is the common method" << endl;
cout << "sizeof(T1) = " << sizeof(T1) << endl;
cout << "sizeof(T2) = " << sizeof(T2) << endl;
return num;
}
int main() {
MyClass<char, int> m;
m.DoSomething<2>();
m.DoSomething<0>();
return 0;
}
Output:
This is the common method
sizeof(T1) = 1
sizeof(T2) = 4
This is ZERO!!!
sizeof(T1) = 1
sizeof(T2) = 4
BTW, do not return num;
from specialization. It doesn't ever know what num
is.