函数模板部分专用化的解决方法
A workaround for partial specialization of function template?
考虑积分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))
}
};
如何编写这样一个函数的停止条件?
每当你问自己"如何模拟函数的部分专业化"时,你可以考虑"重载,让部分排序决定什么重载更专业化"。
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;
}
};
我想您想在注释标记的位置传递-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);
}
用法:
auto p = static_power<5>(2); // 32
只需在类模板中使用static
成员并专门化类模板。不过,为了方便起见,您可能需要创建一个转发函数模板。
相关文章:
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 从 int 中剥离位时,编译器会警告一个转换,但不警告其他转换.有解决方法吗?
- 是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?
- 不为 emplace() 定义构造函数的解决方法
- 删除复制构造函数的 Intel 13.1.2 中不良C++行为的解决方法
- 函数模板部分专业化-有什么解决方法吗
- 带boost的过载模糊性:可选,解决方法
- 继承构造函数和其他变量的解决方法
- C++ 解决方法:"从类型"B*"的表达式初始化类型"C*&"的引用无效"
- 对前向声明类型进行unique_ptr的解决方法
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- 解决方法:QPixmap:在GUI线程之外使用pixmap是不安全的
- CreateProcessWithTokenW 的 cmdline 参数的最大长度是否有解决方法?
- C++双精度作为模板参数的解决方法
- 在参数相关查找之前进行模板替换的任何方法(或解决方法?
- CUDA 内核"Only a single pack parameter is allowed"解决方法?
- dlsym() 解决方法返回类型
- VS2017是否有VLA(可变长度阵列)支持解决方法
- 解决方法:未定义对"class::function"的引用
- 来自 Boost 的 JSON 解析器的警告 C4512 的解决方法