Initializing a constexpr Array with a Pattern

I would like to initialize the constexpr array constexpr template that is generated using the parameters of the variational template. For simplicity, we consider the problem of initializing a static array constexpr unsigned with the sizes of a list of types, say, unsigned, short, char, int, long . How can I do this so that all calculations are done at compile time? I need a solution to play well with a system like C ++, so I cannot use macros.

The best I could come up with is shown below, but compiling using g++ -std=c++11 -Wall -Ofast -S (using g ++ 4.7) and checking the assembly clearly show that the values ​​are g++ -std=c++11 -Wall -Ofast -S stack at runtime. Any ideas? and work great .

Using an array initializer, as shown below, will work if I could somehow say extension n +1 about extension n.

static constexpr unsigned foo[] = { compute_element<Args>::value... };

Edit: Wait, no matter, I had a brainstorm. The line above works fine ...

Here's the answer :

 #include <iostream> template <class... Args> struct foo { static constexpr unsigned bar[] = { sizeof(Args)... }; }; int main() { std::cout << foo<unsigned, short, char, int, long>::bar[2] << std::endl; return 0; } 

Thanks so much for your time!

+2
source share
1 answer

Here's the answer. Keep in mind that due to C ++ restrictions, I believe that this can only be done during the compilation process to create arrays with the same package size of the variation template parameters.

 #include <iostream> template <class... Args> struct foo { static constexpr unsigned bar[] = { sizeof(Args)... }; }; int main() { std::cout << foo<unsigned, short, char, int, long>::bar[2] << std::endl; return 0; } 
+5
source

Source: https://habr.com/ru/post/1238377/


All Articles