我想使用 constexpr 填充枚举数组.数组的内容遵循一定的模式.
I would like to populate an array of enum using constexpr. The content of the array follows a certain pattern.
我有一个将 ASCII 字符集分为四类的枚举.
I have an enum separating ASCII character set into four categories.
enum Type {
Alphabet,
Number,
Symbol,
Other,
};
constexpr Type table[128] = /* blah blah */;
我想要一个包含 128 个 Type
的数组.它们可以在一个结构中.数组的索引将对应于 ASCII 字符,值将是每个字符的 Type
.
I would like to have an array of 128 Type
. They can be in a structure.
The index of the array will be corresponding to the ASCII characters and the value will be the Type
of each character.
所以我可以查询这个数组来找出一个 ASCII 字符属于哪个类别.类似的东西
So I can query this array to find out which category an ASCII character belongs to. Something like
char c = RandomFunction();
if (table[c] == Alphabet)
DoSomething();
我想知道如果没有一些冗长的宏技巧,这是否可行.
I would like to know if this is possible without some lengthy macro hacks.
目前,我通过执行以下操作来初始化表.
Currently, I initialize the table by doing the following.
constexpr bool IsAlphabet (char c) {
return ((c >= 0x41 && c <= 0x5A) ||
(c >= 0x61 && c <= 0x7A));
}
constexpr bool IsNumber (char c) { /* blah blah */ }
constexpr bool IsSymbol (char c) { /* blah blah */ }
constexpr Type whichCategory (char c) { /* blah blah */ }
constexpr Type table[128] = { INITIALIZE };
其中 INITIALIZE
是一些非常冗长的宏 hack 的入口点.类似的东西
where INITIALIZE
is the entry point of some very lengthy macro hacks.
Something like
#define INITIALIZE INIT(0)
#define INIT(N) INIT_##N
#define INIT_0 whichCategory(0), INIT_1
#define INIT_1 whichCategory(1), INIT_2
//...
#define INIT_127 whichCategory(127)
我想要一种方法来填充此数组或包含该数组的结构,而无需此宏 hack...
I would like a way to populate this array or a structure containing the array without the need for this macro hack...
也许类似
struct Table {
Type _[128];
};
constexpr Table table = MagicFunction();
那么,问题是如何编写这个MagicFunction
?
So, the question is how to write this MagicFunction
?
注意:我知道 cctype 和喜欢,这个问题更像是一个 这可能吗?
而不是 这是最好的方法吗?
.
Note: I am aware of cctype and likes, this question is more of a Is this possible?
rather than Is this the best way to do it?
.
任何帮助将不胜感激.
谢谢,
忽略所有问题,索引来救援:
template<unsigned... Is> struct seq{};
template<unsigned N, unsigned... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<unsigned... Is>
struct gen_seq<0, Is...> : seq<Is...>{};
template<unsigned... Is>
constexpr Table MagicFunction(seq<Is...>){
return {{ whichCategory(Is)... }};
}
constexpr Table MagicFunction(){
return MagicFunction(gen_seq<128>{});
}
活生生的例子.
这篇关于在编译时使用 Constexpr 填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!