diff --git a/esphome/components/climate/climate.cpp b/esphome/components/climate/climate.cpp index f0c466203fa..756051d6ce1 100644 --- a/esphome/components/climate/climate.cpp +++ b/esphome/components/climate/climate.cpp @@ -609,35 +609,26 @@ void ClimateDeviceRestoreState::apply(Climate *climate) { climate->publish_state(); } -template bool set_alternative(optional &dst, optional &alt, const T1 &src) { - bool is_changed = alt.has_value(); - alt.reset(); - if (is_changed || dst != src) { - dst = src; - is_changed = true; - } - return is_changed; -} +// Generic template to set one value while clearing its alternative (mutual exclusion) +// Handles both optional and const char* types automatically using compile-time type detection +template bool set_alternative(T1 &dst, T2 &alt, T3 src) { + bool is_changed = false; -// Overload for optional + const char* pointer -template bool set_alternative(optional &dst, const char *&alt, const T &src) { - bool is_changed = (alt != nullptr); - alt = nullptr; - if (is_changed || dst != src) { - dst = src; - is_changed = true; + // Clear the alternative based on its type (pointer or optional) + if constexpr (std::is_pointer_v>) { + is_changed = (alt != nullptr); + alt = nullptr; + } else { + is_changed = alt.has_value(); + alt.reset(); } - return is_changed; -} -// Overload for const char* pointer + optional -template bool set_alternative(const char *&dst, optional &alt, const char *src) { - bool is_changed = alt.has_value(); - alt.reset(); + // Set the destination value if (is_changed || dst != src) { dst = src; is_changed = true; } + return is_changed; }