Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_assert on array values

Is it possible to have a compile-time check on array values?

example:

typedef enum
{
    dummy0 = 0,
    dummy1,
    dummy2
} eDummyEnum;

typedef struct
{
    eDummyEnum name;
    int value;
} sDummyStruct;

const sDummyStruct array[]=
{
    {dummy0, 3},
    {dummy1, 5},
    {dummy2, 6}
}

Is there any possibility to check if array[dummy1].name == dummy1 at compilation time?

like image 452
Mihai Avatar asked Oct 24 '25 10:10

Mihai


1 Answers

Something along these lines, perhaps:

constexpr sDummyStruct array[]=
{
    {dummy0, 3},
    {dummy1, 5},
    {dummy2, 6}
};

constexpr bool checkArray(int index) {
    return (index >= sizeof(array)/sizeof(array[0])) ||
           (array[index].name == index && checkArray(index + 1));          
}

static_assert(checkArray(0), "bad array");

Live demo

like image 90
Igor Tandetnik Avatar answered Oct 25 '25 23:10

Igor Tandetnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!