From 05011a28a0f2a5f1f9e433cfdfd5173fffdd5161 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 7 Apr 2026 14:35:22 -1000 Subject: [PATCH] [core] Support convertible return types in TemplatableFn via trampoline TemplatableFn now accepts stateless lambdas whose return type is convertible to T (e.g., int -> uint8_t). Uses a casting trampoline that reconstructs the stateless lambda via F{} (default-constructible in C++20). Also: - Remove std::move on trivially copyable TemplatableFn (clang-tidy) - Wrap http_request method via cg.templatable() --- esphome/core/automation.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/esphome/core/automation.h b/esphome/core/automation.h index d286782293..fbe7224b70 100644 --- a/esphome/core/automation.h +++ b/esphome/core/automation.h @@ -41,10 +41,16 @@ template class TemplatableFn { public: TemplatableFn() = default; + // Exact return type match — direct function pointer storage template TemplatableFn(F f) requires std::convertible_to : f_(f) {} + // Convertible return type (e.g., int -> uint8_t) — casting trampoline. + // Stateless lambdas are default-constructible in C++20, so F{} recreates the lambda inside + // the trampoline without capturing. This compiles to the same code as a direct call + cast. template - TemplatableFn(F) requires std::invocable &&(!std::convertible_to) = delete; + TemplatableFn(F) requires(!std::convertible_to) && + std::invocable &&std::convertible_to, T> &&std::is_empty_v + &&std::default_initializable : f_([](X... x) -> T { return static_cast(F{}(x...)); }) {} bool has_value() const { return this->f_ != nullptr; }