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);
}
This worked for me:
template<typename T> typename std::enable_if<std::is_pointer<T>::value==false, T>::type sum(const T& a, const T& b)
{
return a + b;
}
template<typename T> typename std::enable_if<std::is_pointer<T>::value, typename std::remove_pointer<T>::type>::type sum(const T a, const T b)
{
return *a + *b;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.