Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I specialize function template?

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;
}
like image 743
user2260241 Avatar asked Sep 11 '26 21:09

user2260241


2 Answers

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
like image 67
jrok Avatar answered Sep 13 '26 09:09

jrok


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);
}
like image 37
AnT Avatar answered Sep 13 '26 11:09

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!