[英]C++: Conditionals in template meta programming
我正在使用 C++ 模板元編程實現一個程序,該程序從編譯時已知的給定數字NUMBER
生成下一個素數。 但是,我目前陷入困境,因為我的模板中需要一個條件值。 所以我在 C++ 中尋找類似三元運算符的東西。
我目前的做法:
#include <iostream>
#ifndef NUMBER
#define NUMBER 6
#endif
template <int P, int K = P - 1>
struct is_prime
{
enum { value = P % K != 0 && is_prime<P, K - 1>::value };
};
template <int P>
struct is_prime<P, 1>
{
enum { value = 1 };
};
template<int P, bool B = is_prime<P>::value>
struct next_prime
{
// This doesn't work
enum { value = ( B ? P : next_prime<P+1>::value )};
};
int main(int argc, char** argv)
{
std::cout << "next prime >= " << NUMBER << ": " << next_prime<NUMBER>::value << std::endl;
return 0;
}
使用g++
編譯時,會導致錯誤:
In instantiation of ‘struct is_prime<503, 4>’:
recursively required from ‘struct is_prime<503, 501>’
recursively required from ‘struct next_prime<3, true>’
required from ‘struct next_prime<2>’
fatal error: template instantiation depth exceeds maximum of 1000 (use ‘-ftemplate-depth=’ to increase the maximum)
有沒有不使用 C++ 11 的好方法?
通常我看到這類問題是通過專業化解決的
template<int P, bool B = is_prime<P>::value>
struct next_prime
{ enum { value = next_prime<P+1>::value }; };
template <int P>
struct next_prime<P, true>
{ enum { value = P }; };
如果您可以使用 C++11 或更新版本,而不是定義value
,我建議來自std::integral_constant
的 inheritance
// std::bool_constant<boolValue> is available starting from C++17;
// in C++11/C++14 you can use std::integral_constant<bool, boolValue>
template <int P, int K = P - 1>
struct is_prime
: public std::bool_constant<P%K && (not is_prime<P, K-1>::value)>
{ };
template<int P>
struct is_prime<P, 2> : public std::bool_constant<P%2>
{ };
template<int K>
struct is_prime<2, K> : public std::true_type
{ };
template<int P, bool B = is_prime<P>::value>
struct next_prime : public next_prime<P+1>
{ };
template <int P>
struct next_prime<P, true> : public std::integral_constant<int, P>
{ };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.