I need to have a way to remove a class member field at compile time based on some condition. I've been trying a few things, such as this:
template <bool Condition, class FieldType> struct Conditional { FieldType Value; };
template <class FieldType> struct Conditional<false, FieldType> {};
But my problem is that members declared this way still use space on the total class size. My goal is to reduce total class size by removing some members depending on compile time condition. Is this possible without class inheritance?
I have access to C++20 if that matters.
I know I have been asking without class inheritance, but it seems like Empty Base Optimization is the only way I could find to do this. To achieve this, I did it this way:
Create two structs, one with the value, one empty:
struct Empty {};
struct SomeField { int something };
And have the class that I want to enable/disable a member field based on some compile time condition derive from std::conditional_t
:
template <class T>
class SomeClass : private std::conditional_t<some_condition<T>, SomeField, Empty> { ... }
Not the best, but it does achieve my goal of reducing the total class size.