Here is my code:
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;
}
It works well. But when I try to add this
template<typename T1, typename T2> template<> int MyClass<T1, T2>::DoSomething<0>()
{
cout << "This is ZERO!!!" << endl;
cout << "sizeof(T1) = " << sizeof(T1) << endl;
cout << "sizeof(T2) = " << sizeof(T2) << endl;
return num;
}
I get compiller errors: invalid explicit specialization before «>» token template-id «DoSomething<0>» for «int MyClass::DoSomething()» does not match any template declaration
I use g++ 4.6.1 What should I do?
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
There are two types of templates in C++, function templates and class templates.
Explanation: Template specialization is used when a different and specific implementation is to be used for a specific data type. In this program, We are using integer and character.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
Unfortunately, you can't specialise a template that's a member of a class template, without specialising the outer template:
C++11 14.7.3/16: In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.
I think your best option is to add the extra parameter to MyClass
, and then partially specialise that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With