Это грустно, но верно: вы не можете явно специализировать шаблон класса, если его включающие шаблоны классов также не являются явно специализированными .Для получения дополнительной информации вы можете прочитать
Ниже я сначала специализировал MyClass и все было сделано.
#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;
}
Вывод:
This is the common method
sizeof(T1) = 1
sizeof(T2) = 4
This is ZERO!!!
sizeof(T1) = 1
sizeof(T2) = 4
EUREKA!Это хорошо работает на 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;
}
Вывод:
This is the common method
sizeof(T1) = 1
sizeof(T2) = 4
This is ZERO!!!
sizeof(T1) = 1
sizeof(T2) = 4
Кстати, не return num;
от специализации.Он никогда не знает, что такое num
.