I would like to conditionally declare a local variable in a function, based on a template bool parameter. So if it is true it should be there, otherwise shouldn't be there in the sense that I don't want that variable to allocate memory on the stack or call its constructor. It could also be a basic type.
I cannot declare it within the constexpr if block because I need persistence between the usages.
I can just declare the variable and add
[[maybe_unused]]
. Then, is there a compiler optimization which guarantees not to allocate memory for the variable?template <bool T> void foo() { [[maybe_unused]] SomeLargeClass x; if constexpr(T) { /* ... do something with x */ } /* ... do something without x */ if constexpr(T) { /* ... do something more with x */ } }
I tried to replace the declaration with
std::enable_if_t<T, SomeLargeClass> x;
but it doesn't work because the
T==false
case fails to provide a type. Why is this not SFINAE?Do I have any other options?
foo
(and refactor anything that does not need the optional variable to a seperate function to avoid duplication) – Mycenae