diff --git a/esphome/components/api/homeassistant_service.h b/esphome/components/api/homeassistant_service.h index 4adda47b71..4343fcd0bb 100644 --- a/esphome/components/api/homeassistant_service.h +++ b/esphome/components/api/homeassistant_service.h @@ -97,28 +97,22 @@ template class HomeAssistantServiceCallAction : public Action void set_service(T service) { this->service_ = service; } - // Initialize FixedVector members - called from Python codegen with compile-time known sizes + // Initialize FixedVector members - called from Python codegen with compile-time known sizes. + // Must be called before any add_* methods; capacity must match the number of subsequent add_* calls. void init_data(size_t count) { this->data_.init(count); } void init_data_template(size_t count) { this->data_template_.init(count); } void init_variables(size_t count) { this->variables_.init(count); } // Keys are always string literals from the Python code generation (e.g., cg.add(var.add_data("tag_id", templ))). // The value parameter can be a lambda/template, but keys are never templatable. - // Using pass-by-value allows the compiler to optimize for both lvalues and rvalues. - template void add_data(std::string key, T value) { - auto &kv = this->data_.emplace_back(); - kv.key = std::move(key); - kv.value = value; + template void add_data(K &&key, V &&value) { + this->add_kv_(this->data_, std::forward(key), std::forward(value)); } - template void add_data_template(std::string key, T value) { - auto &kv = this->data_template_.emplace_back(); - kv.key = std::move(key); - kv.value = value; + template void add_data_template(K &&key, V &&value) { + this->add_kv_(this->data_template_, std::forward(key), std::forward(value)); } - template void add_variable(std::string key, T value) { - auto &kv = this->variables_.emplace_back(); - kv.key = std::move(key); - kv.value = value; + template void add_variable(K &&key, V &&value) { + this->add_kv_(this->variables_, std::forward(key), std::forward(value)); } #ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES @@ -191,6 +185,13 @@ template class HomeAssistantServiceCallAction : public Action void add_kv_(FixedVector> &vec, K &&key, V &&value) { + auto &kv = vec.emplace_back(); + kv.key = std::forward(key); + kv.value = std::forward(value); + } + template static void populate_service_map(VectorType &dest, SourceType &source, Ts... x) { dest.init(source.size());