c++ - 模板非类型模板参数

标签 c++ constexpr c++20 template-templates

我正在尝试使用 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/

相关文章:

c++ - 通过 x86 程序集(嵌入在 C++ 中)对数组进行排序?可能的?

c++ - 将数组中的对象向上移动

C++正则表达式将字符串拆分为数组

c++ - 静态 constexpr 变量与函数

c++ - Constexpr 指针值

c++ - 为什么在定义自定义点对象时需要删除函数?

c++ - Visual Studio 2013 C++ 自动缩进效果不佳

c++ - 我可以定义一个(类型化的)常量,它肯定不会占用可执行文件中的空间吗?

c++ - 在概念中表达对数据成员的概念要求的最佳方式是什么?

c++ - 如何使用参数包和非类型模板值执行部分模板特化?