Skip to content

ESPHome 2026.4.0: Callback registration methods should use templates #228

@bdraco

Description

@bdraco

Summary

ESPHome 2026.4.0 replaces std::function with a lightweight Callback struct in CallbackManager (PR #14853). Existing code continues to compile, but callback registration methods that take std::function now use a less efficient heap-allocation path.

Recommended migration

Convert callback registration methods from std::function to templates:

// Before (still works, but now less efficient)
void add_on_state_callback(std::function<void(float)> &&callback) {
  this->state_callback_.add(std::move(callback));
}

// After (optimal — zero heap allocation for [this] lambdas)
template<typename F> void add_on_state_callback(F &&callback) {
  this->state_callback_.add(std::forward<F>(callback));
}

If you had a separate .cpp definition, move the body inline into the header (templates must be defined in headers).

The template approach is backward compatible with older ESPHome versions — no version guard needed.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions