Search code examples
c++arraysconstantscompile-time-constant

const array of const, to use its elements on array length definitions or give template parameters value


I need a constant array of constants, which its constants (the elements of the constant array of constants) can be used where only a compile time constant can be used, like array length definitions.

E.g:

int a[ my_const_array_of_const[0] ];
int b[ my_const_array_of_const[1] ];

template<int p>
foo() { ... };

foo< my_const_array_of_const[2] >();

I have tried solutions form other answers, but they were not "constant" enough to the compiler not give an error when using them on above situations.

How can I create the "my_const_array_of_const" constant to compile in such situations?

I need it to configure a High-Level Synthesis (HLS) design. For HLS C++ syntax is restricted. No dynamic memory is allowed, hence I need to use static arrays. Besides, all compilation time constants may be used to optimize the hardware accelerator (that is the reason to use template parameters instead of variables).


Solution

  • You could use constexpr (since C++11), which guarantee that the value of the element of the array could be evaluated at compile time. e.g.

    constexpr int my_const_array_of_const[2] {1, 2};
    

    LIVE