【发布时间】:2021-12-22 19:47:50
【问题描述】:
我有以下代码:
#include <cstdint>
template <uint32_t test_value, uint32_t ...Vn>
struct is_prime_tmpl;
template <uint32_t test_value>
struct is_prime_tmpl<test_value> {
static constexpr bool value = true;
};
template <uint32_t test_value, uint32_t V1, uint32_t ...Vn>
struct is_prime_tmpl<test_value, V1, Vn...> {
static constexpr bool value = (test_value % V1 != 0) && is_prime_tmpl<test_value, Vn...>::value;
};
template <uint32_t ...Vn>
struct prime {};
template <uint32_t max_target, uint32_t test_value, class PrimeList>
struct generate_prime_helper_tmpl;
template <uint32_t max_target, uint32_t test_value, uint32_t ...Vn>
struct generate_prime_helper_tmpl<max_target, test_value, prime<Vn...>> {
static constexpr auto result = test_value <= max_target ?
(is_prime_tmpl<test_value, Vn...>::value ?
generate_prime_helper_tmpl<max_target, test_value + 1, prime<Vn..., test_value>>::result : generate_prime_helper_tmpl<max_target, test_value + 1, prime<Vn...>>::result) :
prime<Vn...>();
};
int main() {
static_assert(is_prime_tmpl<2>::value);
static_assert(std::is_same_v<generate_prime_helper_tmpl<2, 2, prime<>>::result, prime<2>);
}
代码试图生成一个素数序列。但它无法在我的本地机器上用 g++10 编译。编译器不会发出任何警告或错误。它只是永远编译。
似乎递归以某种方式被破坏了。但我看不到它。比起实际的解决方案,我更感兴趣的是哪里出了问题。
知道出了什么问题吗?
【问题讨论】:
标签: c++ templates c++17 variadic-templates template-meta-programming