コンパイル時にいくつかの整数素数をチェックする必要があります (ブール値をテンプレート引数として入れるため)。
私はそれをうまくやるコードを書きました:
#include <type_traits>
namespace impl {
template <int n, long long i>
struct PrimeChecker {
typedef typename std::conditional<
(i * i > n),
std::true_type,
typename std::conditional<
n % i == 0,
std::false_type,
typename PrimeChecker<n, (i * i > n ) ? -1 : i + 1>::type
>::type
>::type type;
};
template <int n>
struct PrimeChecker<n, -1> {
typedef void type;
};
} // namespace impl
template<int n>
struct IsPrime {
typedef typename impl::PrimeChecker<n, 2>::type type;
};
template<>
struct IsPrime<1> : public std::false_type {
};
~1000000 までの数値で機能し、10 9のエラーで失敗します
prog.cpp:15:23: error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum) instantiating ‘struct impl::PrimeChecker<1000000000, 901ll>’
>::type type;
^
prog.cpp:15:23: recursively required from ‘struct impl::PrimeChecker<1000000000, 3ll>’
prog.cpp:15:23: required from ‘struct impl::PrimeChecker<1000000000, 2ll>’
prog.cpp:24:54: required from ‘struct IsPrime<1000000000>’
prog.cpp:32:41: required from here
深度制限を増やすことはできません。私が使用する深さを減らすことはどういうわけか可能ですか?
私が達成したいこと:テンプレートの深さ制限900と深さ制限512でコンパイル文字列を変更せずに、コンパイル時に定数素数であることを確認する必要がありconstexpr
ます(私のg ++のデフォルト)。すべての正の int32 に対して、または少なくとも 10 9 +9までの数値に対して機能するはずです。