テンプレート非型テンプレートパラメータ

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