問題描述
我想使用 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 填充數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!