[core] Fix compile-time loop() detection for multiple inheritance (#14411)

This commit is contained in:
J. Nick Koston
2026-03-02 19:11:47 +00:00
committed by GitHub
parent 2fa244715d
commit cb232d8288
2 changed files with 12 additions and 4 deletions
+10 -3
View File
@@ -118,6 +118,14 @@ void original_setup(); // NOLINT(readability-redundant-declaration) - used by c
namespace esphome {
/// SFINAE helper: detects whether T overrides Component::loop().
/// When &T::loop is ambiguous (multiple inheritance with separate loop() methods),
/// the ambiguity itself proves an override exists, so the true_type default is correct.
template<typename T, typename = void> struct HasLoopOverride : std::true_type {};
template<typename T>
struct HasLoopOverride<T, std::void_t<decltype(&T::loop)>>
: std::bool_constant<!std::is_same_v<decltype(&T::loop), decltype(&Component::loop)>> {};
// Teardown timeout constant (in milliseconds)
// For reboots, it's more important to shut down quickly than disconnect cleanly
// since we're not entering deep sleep. The only consequence of not shutting down
@@ -544,10 +552,9 @@ class Application {
#endif
/// Register a component, detecting loop() override at compile time.
/// The template resolves &T::loop vs &Component::loop as a constexpr bool
/// and forwards it to register_component_impl_ which stores it in component_state_.
/// Uses HasLoopOverride<T> which handles ambiguous &T::loop from multiple inheritance.
template<typename T> void register_component_(T *comp) {
this->register_component_impl_(comp, !std::is_same_v<decltype(&T::loop), decltype(&Component::loop)>);
this->register_component_impl_(comp, HasLoopOverride<T>::value);
}
void register_component_impl_(Component *comp, bool has_loop);
+2 -1
View File
@@ -517,9 +517,10 @@ async def _add_looping_components() -> None:
return
# Build constexpr sum for the exact count, deduplicating by type
# Uses HasLoopOverride<T> which handles ambiguous &T::loop from multiple inheritance
type_counts = Counter(entries)
terms = [
f"({count} * !std::is_same_v<decltype(&{cpp_type}::loop), decltype(&Component::loop)>)"
f"({count} * HasLoopOverride<{cpp_type}>::value)"
for cpp_type, count in type_counts.items()
]
constexpr_expr = " + \\\n ".join(terms)