템플릿 비 유형 템플릿 매개 변수

Dec 07 2020

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 Kostas Dec 07 2020 at 22:22

템플릿 템플릿 매개 변수에 대한 인수를 직접 참조 할 수 없습니다. 범위 내에 있지 않습니다. 그러나 다음과 같이 할 수 있습니다.

#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() {
  size_t pow = pow10<3>;
  std::cout << pow << std::endl; // prints 1000
}

즉, 구현하는 더 간단한 방법이 있습니다 pow10.

template <size_t pow>
struct pow10 { static constexpr size_t value = 10 * pow10<pow-1>::value; };
template <> struct pow10<0> { static constexpr size_t value = 1; };
int main() {
  size_t pow = pow10<3>::value;
  std::cout << pow << std::endl; //prints 1000
}
4 Mestkon Dec 07 2020 at 22:23

다음과 같이 할 수 있습니다.

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