pao*_*olo 3 c++ templates c++-concepts c++20
让我们考虑以下用于阶乘函数的编译时计算的代码:
#include <concepts>
template <std::integral auto num>
struct factorial {
constexpr static auto val{num * factorial<num - 1>::val};
};
// Note: This only specializes the class for (int)0
template <>
struct factorial<0> {
constexpr static auto val{1};
};
// ...
factorial<4>::val; // Ok: 24
factorial<4u>::val; // error: template instantiation depth exceeds maximum of 900
// This makes sense: There's no factorial<0u> specialization.
Run Code Online (Sandbox Code Playgroud)
factorial<0>有没有办法为所有整型(即满足 的所有类型)引入专门化std::integral?
当然,我想避免实际写出专业化factorial<0u>,factorial<0l>等等。
您可以部分专门化任何比较等于的值,而不是显式专门化0(即int带有 value ) :00
template <std::integral auto I> requires (I == 0)
struct factorial<I> {
static constexpr auto val = 1;
};
Run Code Online (Sandbox Code Playgroud)
如果您愿意,也可以这样拼写:
template <class T, T I> requires (I == 0)
struct factorial<I> {
static constexpr auto val = 1;
};
Run Code Online (Sandbox Code Playgroud)
但我不认为有办法推断出T{0}价值。
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |