mirror of
https://github.com/esphome/esphome.git
synced 2025-09-13 00:32:20 +01:00
Move TemplatableValue helper class to automation.h (#2511)
This commit is contained in:
@@ -255,63 +255,6 @@ struct is_callable // NOLINT
|
||||
static constexpr auto value = decltype(test<T>(nullptr))::value; // NOLINT
|
||||
};
|
||||
|
||||
template<typename T, typename... X> class TemplatableValue {
|
||||
public:
|
||||
TemplatableValue() : type_(EMPTY) {}
|
||||
|
||||
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_{};
|
||||
};
|
||||
|
||||
template<typename... X> class TemplatableStringValue : public TemplatableValue<std::string, X...> {
|
||||
public:
|
||||
TemplatableStringValue() : TemplatableValue<std::string, X...>() {}
|
||||
|
||||
template<typename F, enable_if_t<!is_callable<F, X...>::value, int> = 0>
|
||||
TemplatableStringValue(F value) : TemplatableValue<std::string, X...>(value) {}
|
||||
|
||||
template<typename F, enable_if_t<is_callable<F, X...>::value, int> = 0>
|
||||
TemplatableStringValue(F f)
|
||||
: TemplatableValue<std::string, X...>([f](X... x) -> std::string { return to_string(f(x...)); }) {}
|
||||
};
|
||||
|
||||
void delay_microseconds_accurate(uint32_t usec);
|
||||
|
||||
template<typename T> class Deduplicator {
|
||||
|
Reference in New Issue
Block a user