mirror of
https://github.com/Threnklyn/esphome-dev.git
synced 2026-06-03 19:38:30 +02:00
Move TemplatableValue helper class to automation.h (#2511)
This commit is contained in:
@@ -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.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user