Как я могу обернуть свои перечисления, чтобы их можно было использовать с обработчиком? Сам обработчик может не быть шаблонным.
Вот схема структуры:
Код: Выделить всё
// Ui Layer
class UiList {
public:
UiList(std::vector strings, ToBeDefinedIntLikeValue& index);
// called when underlying value changes
void updateUi()
{
displayString(mStrings[mIndex.get()]);
}
// called by UI, when user selects
void updateValue(int newIndex)a different string
{
mIndex.set(newIndex);
}
};
//////
// Generated code
enum class Colors { red, green, blue };
enum class Animals { cat, dog, goose };
//////
// Data layer
struct Storage{
Colors color;
Animals animal;
};
/////
// Coupling layer
template
UiList createUiList(E& e, std::vector values) {
// Initialize UiList, so that it can convert the e values to indices
}
//// Usage
mUi.addList(createUiList(mStorage.color, {"red", "green",
"blue"});
mUi.addList(createUiList(mStorage.animal, {"cat", "dog", "goose"});
Код: Выделить всё
#include
enum class E1 {
a,b,c
};
enum class E2 {
d,e,f
};
struct Wrapper
{
using Getter = std::function;
using Setter = std::function;
int get() const { return getter_(); }
void set(int v) { setter_(v); }
Getter getter_;
Setter setter_;
};
template
auto createWrapper(E& e) {
return Wrapper{
[&e]{ return static_cast(e); },
[&e](int v) { e = static_cast(v); }
};
}
// This function cannot be templated
void handleValues(Wrapper w)
{
int i = w.get();
w.set(i*2);
}
int main()
{
E1 e1 = E1::a;
E2 e2 = E2::d;
handleValues(createWrapper(e1));
handleValues(createWrapper(e2));
}
Все мои попытки терпят неудачу, потому что я не могу найти способ сохранить фактическое перечисление для получения/установки, не фиксируя его в лямбда-выражении или не используя шаблон.
Подробнее здесь: https://stackoverflow.com/questions/797 ... ass-to-int
Мобильная версия