提问者:小点点

模板非类型模板参数


我正在尝试使用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上编译。

是否可以指定模板非类型模板参数?或者,也可以递归地编写它,但是最好知道是否可以像上面那样编写它。

请注意,该问题看起来类似于模板模板非类型参数,但非类型模板参数被放置在嵌套模板参数列表中,而不是主参数列表中。


共2个答案

匿名用户

你可以这样做:

#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);

匿名用户

不能直接引用参数到模板模板参数。它们不在范围内。但你可以这样做:

#include <utility>

template <class>
class pow10_helper {};

template <template <typename T, T ...> class IntSeq, class T, T ... Ints>
struct pow10_helper<IntSeq<T, Ints...>> {
  static constexpr long value = ((Ints, 10) * ...);
};

template <size_t pow>
static constexpr long pow10 = pow10_helper<std::make_index_sequence<pow>>::value;

#include <iostream>
int main() {
  long pow = pow10<3>;
  std::cout << pow; // prints 1000
}