【发布时间】:2018-07-01 04:30:37
【问题描述】:
鉴于下面的示例,压缩模板特化以使一两条指令足以定义所有特殊值的最佳方法是什么?也许是可变参数?
enum class PositiveDigit // Not necessarily sequential
{ One=1, Two, Three, Four, Five, Six, Seven, Eight, Nine };
// Base class template
template <std::underlying_type_t<PositiveDigit>>
struct IsNum
{ static constexpr bool aPrimeDigit = false; };
// Specialized class templates to define which positive digits are prime
// HOW TO BEST COMBINE/CONDENSE THESE? VARIADIC?? Ideally, something like:
// template <PositiveDigit::Two, PositiveDigit::Three, ……> …… OR,
// template <> …… (PositiveDigit::Two, PositiveDigit::Three, ……) …… OR??
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Two)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Three)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Five)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Seven)>
{ static constexpr bool aPrimeDigit = true; };
int main() {
// Note: It's perfectly okay to pass integers beyond the range of the
// enum class, they'll simply provide a false result
IsNum<-5>::aPrimeDigit; // false
IsNum<13>::aPrimeDigit; // false
IsNum< 7>::aPrimeDigit; // true!
}
请假设enum 必须保持强类型。现实世界的问题有很大的enum class,许多潜在的专业化,与数字或素数无关;这只是一个简单的例子。
这些类似的问题似乎无法解决手头的问题(除非我遗漏了什么):
【问题讨论】:
-
有趣的是零是正数,一是质数。
-
看看如何测试一个值是否在integer_sequence中,然后写一个模板取integer_sequence的素数?哦,还有一个不是素数。
-
好的,已修复以安抚迂腐。还要提到枚举不一定是顺序的
标签: c++ c++11 templates c++14 variadic-templates