I need to check is some integer prime in compile time (to put the boolean value as template argument).
I've write code that do it well:
#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 {
};
It works for numbers to ~1000000 and fails with error for 109
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
I can't increase the depth limit. Is it somehow possible to decrease depth I use?
Thing I want to achive: I need to check is constant prime in compile time without changing compilation string with template depth limit 900 and constexpr
depth limit 512. (default for my g++). It should work for all positive int32's or at least for numbers up to 109+9
constexpr
. (I'm looking at you VS2012...) – HowlingN
. (E.g. as partial specializations of some template for prime numbers) – Declivityconstexpr
is not a guarantee of compile-time evaluation. It may or may not be evaluated at compile time. Unless it is used in a place where the value is required at compile-time (i.e. template argument). – Decry