相关疑难解决方法(0)

在编译时使用Constexpr填充数组

我想使用constexpr填充一个枚举数组.阵列的内容遵循某种模式.

我有一个枚举将ASCII字符集分为四类.

enum Type {
    Alphabet,
    Number,
    Symbol,
    Other,
};

constexpr Type table[128] = /* blah blah */;
Run Code Online (Sandbox Code Playgroud)

我想有一个128的数组Type.它们可以是一个结构.数组的索引将对应于ASCII字符,值将是Type每个字符的值.

所以我可以查询这个数组,找出ASCII字符属于哪个类别.就像是

char c = RandomFunction();
if (table[c] == Alphabet) 
    DoSomething();
Run Code Online (Sandbox Code Playgroud)

我想知道如果没有一些冗长的宏观黑客,这是否可行.

目前,我通过执行以下操作来初始化表.

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 */ } …
Run Code Online (Sandbox Code Playgroud)

c++ templates constexpr c++11

20
推荐指数
3
解决办法
1万
查看次数

C++ 11:具有对数评估深度的编译时数组

应用程序图像的实现具有通过由编译器计算其指数的函数初始化它的元素,并已存储在数据部分的结果的C++ 11阵列的一种方式(.RODATA)是使用模板,部分特和constexpr如下:

#include <iostream>
#include <array>
using namespace std;

constexpr int N = 1000000;
constexpr int f(int x) { return x*2; }

typedef array<int, N> A;

template<int... i> constexpr A fs() { return A{{ f(i)... }}; }

template<int...> struct S;

template<int... i> struct S<0,i...>
{ static constexpr A gs() { return fs<0,i...>(); } };

template<int i, int... j> struct S<i,j...>
{ static constexpr A gs() { return S<i-1,i,j...>::gs(); } };

constexpr auto X = S<N-1>::gs();

int main()
{
        cout << …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

17
推荐指数
1
解决办法
1178
查看次数

标签 统计

c++ ×2

c++11 ×2

constexpr ×1

templates ×1