为什么我不能专门化功能模板?

时间:2013-07-13 09:30:39

标签: c++ templates template-specialization

为什么我可以专门化课程A,但不能以同样的方式专门化函数sum? 如何使此代码有效?提前谢谢。

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;
}

3 个答案:

答案 0 :(得分:3)

您不能部分专门化功能模板,标准禁止它。但你可以简单地超载它:

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

答案 1 :(得分:2)

正如已经陈述的那样,功能模板不能部分专业化。

在您确实需要部分特化(而不是重载)的情况下,有几种解决方法。我只是想在这样的情况下添加它,通常可以字面上通过将调用委托给类模板来实现部分专业行为

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);
}

答案 2 :(得分:1)

这对我有用:

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;
}
相关问题