C++ Compile time conditional struct member variables

Saleem Ahmad
2 min readOct 10, 2020

--

C++ has rich set of features to do compile time calculations and optimizations to generate a better code. In one of code segment I have very large data structure in which few member variables are not used based on compile time if constexpr condition, but these variables are logged in the log line. So it looks something like this

Now this code has a few problems which i feel, like if kDebug = false, then

  1. b[16] will be there in struct Data even though i am not using it anymore increasing the memory foot print of the structure.
  2. This will have impact on caches as the unused member will be prefetched in the cache using space on my tiny little cache and polluting it with some unused data.
  3. The log line will be accessing the unused data again polluting my cache with unwanted data. The log line can be pushed inside the if contexpr block, but that is code repetition which i want to avoid.

Now to solve these problem we can use purely the rich set of type traits provided by C++20 and get away with unused data. To solve first we can

  • Use std::conditional_t to either include the Debug variable or an Empty struct.
  • The problem of conditional accessing the member variable can be solved with SFINAE for template overload resolution for the get_b() function. Something like this

Combining everything, I have done so far code looks like

If I run the code in godbolt (https://godbolt.org/z/5ev3sf), and change the compile time config parameter, I can see the struct size changes and the code compile correctly without changing a single line of code.

--

--