Move TemplatableValue helper class to automation.h (#2511)

This commit is contained in:
Oxan van Leeuwen
2021-10-15 22:05:11 +02:00
committed by GitHub
parent 653a3d5d11
commit c82d5d63e3
3 changed files with 58 additions and 65 deletions
+43 -7
View File
@@ -17,14 +17,50 @@ namespace esphome {
#define TEMPLATABLE_VALUE(type, name) TEMPLATABLE_VALUE_(type, name)
#define TEMPLATABLE_STRING_VALUE_(name) \
protected: \
TemplatableStringValue<Ts...> name##_{}; \
\
public: \
template<typename V> void set_##name(V name) { this->name##_ = name; }
template<typename T, typename... X> class TemplatableValue {
public:
TemplatableValue() : type_(EMPTY) {}
#define TEMPLATABLE_STRING_VALUE(name) TEMPLATABLE_STRING_VALUE_(name)
template<typename F, enable_if_t<!is_callable<F, X...>::value, int> = 0>
TemplatableValue(F value) : type_(VALUE), value_(value) {}
template<typename F, enable_if_t<is_callable<F, X...>::value, int> = 0>
TemplatableValue(F f) : type_(LAMBDA), f_(f) {}
bool has_value() { return this->type_ != EMPTY; }
T value(X... x) {
if (this->type_ == LAMBDA) {
return this->f_(x...);
}
// return value also when empty
return this->value_;
}
optional<T> optional_value(X... x) {
if (!this->has_value()) {
return {};
}
return this->value(x...);
}
T value_or(X... x, T default_value) {
if (!this->has_value()) {
return default_value;
}
return this->value(x...);
}
protected:
enum {
EMPTY,
VALUE,
LAMBDA,
} type_;
T value_{};
std::function<T(X...)> f_{};
};
/** Base class for all automation conditions.
*