using
defines an alias, it does not specialize anything. using
defines aliases for classes, types, etc... Aliases, and specializations, are two completely different things.
f()
is not a class. It's a method. Classes, various types, and things of this nature, can be aliased with using
or typedef
. But not functions or methods.
If you want to specialize the class method, define the specialization for the method outside the class:
template<>
int S::f<1>()
{
return 0; // Or whatever your specialization function needs to do.
}
If you want an alias for a function, this is basically a wrapper:
int f1()
{
return f<1>();
}
So, calling f1()
now calls the specialized method.
If you want to both specialize and "alias" the static class method, there's an extra twist. You can't define the wrapper inline, in the class. This is because the specialization is not declared yet. You'll have to declare the wrapper; and then define it after defining the specialization:
#include <iostream>
struct S
{
template<int x> static int f() { return x; }
static int f1();
};
template<>
int S::f<1>()
{
return 0;
}
inline int S::f1()
{
return f<1>();
}
int main()
{
std::cout << S::f<4>() << std::endl;
std::cout << S::f<1>() << std::endl;
}
inline
is needed if this actually goes into a header file, to avoid duplicate symbols at link time. If the whole thing goes into a single translation unit, you can drop inline
.