【发布时间】:2013-08-20 15:35:31
【问题描述】:
我需要检查编译时是否有一些整数素数(将布尔值作为模板参数)。
我写的代码做得很好:
#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 的数字,但失败并出现错误 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
我无法增加深度限制。有没有可能减少我使用的深度?
我想要实现的目标:我需要检查编译时是否为常数素数无需更改编译字符串,模板深度限制为 900,constexpr 深度限制为 512。 (我的 g++ 的默认设置)。它应该适用于所有正 int32 或至少适用于高达 109+9
【问题讨论】:
-
为什么不使用 constexpr?看看这里:cpptruths.blogspot.no/2011/07/…
-
所以,你被 C++ 大师控制了,带着... 作业... :)
-
@olevegard 我不知道,但并非所有声称支持 C++11 的编译器都有
constexpr。 (我在看你VS2012...) -
@olevegard,嘿,我只是忘记了它的存在。您可以将其发布为答案吗?
-
@sehe,信不信由你,我确实自己编写了这段代码,这是我自己的想法。我被我控制了吗?可能是。但我不会说他(我)是大师
标签: c++ templates c++11 template-meta-programming compile-time