ルックアップテーブルにコンパイル時に計算された整数を入力したい:
#include <iostream>
#include <type_traits>
template <int x> using number = std::integral_constant<int,x>;
template <int n> struct factorial : number<n * factorial<n-1>::value> {};
template <> struct factorial<0> : number<1> {};
int get_factorial(int x) {
if (x < 1) return -1;
if (x > 5) return -1;
static constexpr int lookup_table[] = {
factorial<1>::value,
factorial<2>::value,
factorial<3>::value,
factorial<4>::value,
factorial<5>::value
};
return lookup_table[x-1];
}
int main() {
int x;
std::cin >> x;
std::cout << get_factorial(x) << "\n";
}
これは少数の要素には問題ありませんが、ルックアップテーブルに多数の要素が含まれている場合はどうすればよいですか?各要素を明示的に記述せずに配列にデータを入力するにはどうすればよいですか?
これfactorial
は一例です。より現実的なシナリオでは、ルックアップテーブルに最大1000個の要素を格納したいと思います。
C ++ 14では、次のものを使用できますstd::integer_sequence
。
template <int... S>
constexpr std::array<int, sizeof...(S)> get_lookup_table_impl(std::integer_sequence<int, S...>)
{
return { factorial<S>::value... };
}
template <int S>
constexpr auto get_lookup_table()
{
return get_lookup_table_impl(std::make_integer_sequence<int, S>{});
}
ここで完全に機能する例を参照してください。
秘訣はstd::make_integer_sequence<int, S>{}
、のインスタンスを作成することですstd::integer_sequence<int, S...>
。したがって、ヘルパー関数get_lookup_table_impl
はそのパラメーターパックを推測することができます。次に、それをfactorial<S>::value...
解凍し、の各値をS
に渡しますfactorial
。中括弧で覆われているため、これを使用してあらゆる種類のstdコンテナを初期化できます。使用しましたがstd::array
、何でも使用できます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加