我正在尝试使用 C++20 功能简洁地编写一个 constexpr 常量。
#include <utility>
template <template <typename T, T ... Ints> std::integer_sequence<T, Ints...> I>
static constexpr long pow10_helper = ((Ints, 10) * ...);
template <std::size_t exp>
static constexpr long pow10 = pow10_helper< std::make_index_sequence<exp> >;
static_assert(pow10<3> == 1000);
但它既不在 GCC 上也不在 clang 上编译。
是否可以指定模板非类型模板参数? 或者,可以递归地编写它,但很高兴知道是否可以像上面那样编写它。
请注意,这个问题看起来类似于 Template template non-type parameter 但是非类型模板参数被放置在嵌套模板参数列表中,而不是主参数列表中。
最佳答案
你可以这样做:
#include <utility>
template<class T>
static constexpr long pow10_helper;
template<class T, T... Is>
static constexpr long pow10_helper<std::integer_sequence<T, Is...>> = ((Is, 10) * ...);
template <std::size_t exp>
static constexpr long pow10 = pow10_helper<std::make_index_sequence<exp> >;
static_assert(pow10<3> == 1000);
关于c++ - 模板非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65184255/