Why could I specialize class A, but can't specialize function sum in the same way?
How do I make this code work? Thanks in advance.
template<class T>
class A
{
};
template<class T>
class A<T*>
{
};
template<class T>
T sum(const T& a, const T& b)
{
return a + b;
}
template<class T>
T sum<T*> (const T* a, const T* b)
{
return *a + *b;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 1, b = 2;
cout << sum<int>(&a, &b);`
A<int> c;
A<int*> d;
return 0;
}
You can't partialy specialize function templates, the standard forbids it. But you can simply overload it:
template<class T>
T sum(const T& a, const T& b);
template<class T>
T sum (const T* a, const T* b); // note the absence of <T*> here
As it has already been stated, function templates cannot be partially specialized.
There are several workarounds though in situations where you really need partial specialization (instead of overload). I just wanted to add that in cases like that you can often literally implement partially specialized behavior by delegating the call to a class template
template<typename T> struct sum_impl {
static T sum(const T& a, const T& b) {
return a + b;
}
};
template<typename T> struct sum_impl<T*> {
static T sum(const T* a, const T* b) {
return *a + *b;
}
};
template <typename T>
T sum(const T& a, const T& b)
{
return sum_impl<T>::sum(a, b);
}
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