Vin*_*ent 0 c++ templates metaprogramming partial-specialization c++11
考虑以下关于积分pow的元函数(这只是一个例子):
class Meta
{
template<int N, typename T> static constexpr T ipow(T x)
{
return (N > 0) ? (x*ipow<N-1>(x))
: ((N < 0) ? (static_cast<T>(1)/ipow<N>(x))
: (1))
}
};
Run Code Online (Sandbox Code Playgroud)
如何为这样的函数写停止条件?
Joh*_*itb 10
无论何时你问自己"如何模拟函数的局部特化",你可以认为"重载,让部分排序决定什么过载更专业化".
template<int N>
using int_ = std::integral_constant<int, N>;
class Meta
{
template<int N, typename T> static constexpr T ipow(T x)
{
return ipow<N, T>(x, int_<(N < 0) ? -1 : N>());
}
template<int N, typename T> static constexpr T ipow(T x, int_<-1>)
{
// (-N) ??
return static_cast<T>(1) / ipow<-N>(x, int_<-N>());
}
template<int N, typename T> static constexpr T ipow(T x, int_<N>)
{
return x * ipow<N-1>(x, int_<N-1>());
}
template<int N, typename T> static constexpr T ipow(T x, int_<0>)
{
return 1;
}
};
Run Code Online (Sandbox Code Playgroud)
我想你想通过-N而不是N在评论标记的位置.
一个简单的版本可能是这样的:
template <typename T, unsigned int N> struct pow_class
{
static constexpr T power(T n) { return n * pow_class<T, N - 1>::power(n); }
};
template <typename T> struct pow_class<T, 0>
{
static constexpr T power(T) { return 1; }
};
template <unsigned int N, typename T> constexpr T static_power(T n)
{
return pow_class<T, N>::power(n);
}
Run Code Online (Sandbox Code Playgroud)
用法:
auto p = static_power<5>(2); // 32
Run Code Online (Sandbox Code Playgroud)