template<typename T>
struct A{
void method1(){}
};
template<>
struct A<int>{
void method2(){}
};
Will A<int>
have both method1 and method2? And A<float>
will only have method1
?
template<typename T>
struct A{
void method1(){}
};
template<>
struct A<int>{
void method2(){}
};
Will A<int>
have both method1 and method2? And A<float>
will only have method1
?
Each specialization brings an entirely new data type into existence (or an entirely new template, if the specialization is only partial). From the Standard (C++11):
And:
The above is stated in the context of partial specializations, but it applies to explicit specializations (as in your case) as well, although the Standard does not say this very clearly.
Also note that you need not only declare all member functions that you want in a specialization, but you need to define them, too (here, the Standard is very clear even about explicit specializations):
So, indeed,
A<int>
will only havemethod2()
, andA<float>
will only havemethod1()
as member. Furthermore, if you were to introducemethod1()
in theA<int>
specialization as well, it needs not have the same argument types or return type asA<float>::method1()
.See @aschepler's answer for possible ways to avoid having to rewrite the template definition for the
int
case.The specialisation replaces the generic template. So
A<int>
will only havemethod2()
and, of course,A<double>
will only havemethod1()
.@jogojapan's answer explains what the language does. Here's a couple workarounds if you do want to add new members for a specific specialization:
Now
A<int>
has membersmethod1
andmethod2
, butA<float>
has nomethod2
.OR (if you can modify the primary template)...
The
template<int N>
andN==N
parts make surestd::enable_if
has a dependent value and therefore doesn't complain until somebody actually tries to useA<T>::method2
with an incorrectT
parameter.And since this question and answer seem to still be getting attention, a much later edit to add that in C++20, you can simply do: