Metaprogramming with constexpr or struct

We just started learning metaprogramming patterns in C ++ 11. As an exercise, we wrote a program that displays a binary representation of an int value. We came up with two possible implementations. The first uses recursion with enumeration values, while the second method uses the constexpr function.

Our expectation was that both implementations lead to the execution of the same size. However, the first implementation results in 9064 bytes, while the second has 9096 bytes. We are not against the small difference in bytes, but we do not understand what causes the difference.

We compiled the program using GCC 4.8.2 without the optimization flag, however, the -O2 flag was found in the same results.

#include <iostream> using namespace std; template <int val> struct Bin { enum { value = 10 * Bin<(val >> 1)>::value + (val & 1) }; }; template <> struct Bin<0> { enum { value = 0 }; }; constexpr int bin(int val) { return val == 0 ? 0 : (10 * bin(val >> 1) + (val & 1)); } int main() { // Option 1 cout << Bin<5>::value << '\n' << Bin<27>::value << '\n'; // Option 2 cout << bin(5) << '\n' << bin(27) << '\n'; } 
+5
source share
1 answer

constexpr functions can be evaluated at compile time. They are not required.

For the code you provided, the compiler does not really do this, and bin receives a call at runtime; this means that the function cannot be thrown out of the assembly. Explicitly requiring the values ​​to be constexpr with

 constexpr auto i = bin(5), j = bin(27); 

bin calls are made at compile time, as shown here . Via

  cout << bin(5) << '\n' << bin(27) << '\n'; 

corresponding emitted code

 movl $5, %edi # Parameter callq bin(int) # Here the call to bin movl std::cout, %edi movl %eax, %esi callq std::basic_ostream<char, std::char_traits<char> >::operator<<(int) [...] movl $27, %edi # parameter callq bin(int) # call to bin movq %rbx, %rdi movl %eax, %esi callq std::basic_ostream<char, std::char_traits<char> >::operator<<(int) 

When the call is canceled, the size is the same for both versions.

+3
source

All Articles