Re: Class member specialization
On 26 =DAn, 15:21, bra...@gmail.com wrote:
Hello
I need some help with template functions specialization. Consider the
following code:
#include <iostream>
template<class T, int I>
class C {
public:
int Member(void);
};
template<class T, int I>
int C<T,I>::Member(void) {
T t();
return I;
}
int main(void) {
C<int,3> c;
std::cout << c.Member() << std::endl;
return 0;
}
So far, everything works fine. When I provide explicit specialization,
everything is OK too:
template<>
int C<int,5>::Member(void) {
return 555;
}
The problem appears, when I try to partially specialize that function:
template<class U>
int C<U,3>::Member(void) {
U u();
return 6;
}
I got some errors under Visual C++ Express:
-) error C3860: template argument list following class template name
must list parameters in the order used in template parameter list
-) error C2995: 'int C<T,I>::Member(void)' : function template has
already been defined
-) error C2264: 'C<T,I>::Member' : error in function definition or
declaration; function not called
and under Comeau online compiler:
-) "ComeauTest.c", line 21: error: template argument list must match
the parameter list
int C<U,3>::Member(void) {
Is this possible to do in standard C++ way? Thanks for your help.
braton
You cannot partially specialize function or method. it works only for
classes/structs. As workaround you can implement your method as call
of static method of some struct and specialize this class:
template<typename T, int I>
struct MethodImplementation
{
static void Method()
{
// Default implementation
}
};
template<typename T>
struct MethodImplementation<T, 10>
{
static void Method()
{
// Specialized implementation
}
};
template<typename T, int I>
class MyClass
{
public:
// ...
void Method()
{
MethodImplementation<T, I>::Method();
}
};
It has no impact on speed of compiled code (all additional methods are
inlined), but it has worse readability.