当您发现自己需要部分专门化功能模板时(请注意,这并不意味着 在这种情况下您需要,如 DyP's answer 所示),您可以求助于重载(请参阅此答案末尾的最后更新),或者,如果不可能,将该函数模板包装到类模板中,并使用静态的非模板成员函数替换您的原始函数模板(及其特化):
namespace detail
{
template<class T, int N>
struct helper
{
static constexpr T pow(const T x){
return helper<T, N-1>::pow(x) * x;
}
};
template<class T>
struct helper<T, 1> // Unnecessary specialization! (see the edit)
{
static constexpr T pow(const T x){
return x;
}
};
template<class T>
struct helper<T, 0>
{
static constexpr T pow(const T x){
return 1;
}
};
}
然后,您可以提供一个辅助函数模板,该模板代表您的辅助类模板的特化:
template<int N, class T>
T constexpr pow(T const x)
{
return detail::helper<T, N>::pow(x);
}
这是live example。
编辑:
注意,N == 1 的特化实际上是不必要的。我将其保留在原始文本中,因为此答案的目的主要是展示如何解决部分专业化功能模板的不可能性一般 - 所以我逐段翻译了原始程序。
正如 Dyp in the comments 所指出的,这已经足够了:
namespace detail
{
template<class T, int N>
struct helper
{
static constexpr T pow(const T x){
return helper<T, N-1>::pow(x) * x;
}
};
template<class T>
struct helper<T, 0>
{
static constexpr T pow(const T x){
return 1;
}
};
}
更新:
进一步说明,请记住,即使您可以特化函数模板(例如,使用显式 - 而非部分 - 特化),这样做通常也不是一个好主意,因为函数模板特化通常不会像预期的那样表现。
大多数似乎需要函数模板特化的情况实际上可以通过重载实现,由众所周知的技术(如标签调度)提供支持。 Potatoswatterin the comments提出了一个例子,指出std::integral_constant可以用在这种情况下:
template<class T>
inline constexpr T pow(const T x, std::integral_constant<T, 0>){
return 1;
}
template<class T, int N>
inline constexpr T pow(const T x, std::integral_constant<T, N>){
return pow(x, std::integral_constant<T, N-1>()) * x;
}
template<int N, class T>
inline constexpr T pow(const T x)
{
return pow(x, std::integral_constant<T, N>());
}
但是,所有这些关于“如何解决似乎需要函数模板部分专业化的问题”的指导方针,在真正需要时都应该考虑在内。在这个具体的案例中,正如 DyP 在他的回答中所表明的那样,他们不是。