'Use of non-static member function for this Arduino library
In an Arduino project (C++) I use the LiquidMenu library and I have difficulties to integrate this class in my own. The example provided are too simple for a real scenario.
Some code that does not compile:
main.cpp
const int rs = 3, en = 0, d4 = 4, d5 = 30, d6 = 12, d7 = 6;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
Menu menu(&lcd);
void setup() { }
void loop() { }
header
class Menu
{
public:
Menu(LiquidCrystal *lcd);
private:
int _myvar;
LiquidCrystal *_lcd;
LiquidMenu _menu;
LiquidScreen _screenSetCC1;
LiquidLine line1_setupCC1;
LiquidLine line2_setupCC1;
void editIntPlus();
};
cpp
Menu::Menu(LiquidCrystal *lcd) : _lcd(lcd), _menu(*_lcd),
line1_setupCC1(0, 0, "Set CC #1"),
line2_setupCC1(0, 1, _myvar)
{
line2_setupCC1.attach_function(1, editIntPlus);
_screenSetCC1.add_line(line1_setupCC1);
_screenSetCC1.add_line(line2_setupCC1);
_menu.add_screen(_screenSetCC1);
}
void Menu::editIntPlus()
{
_myvar++;
}
first error is:
error: invalid use of non-static member function 'void Menu::editIntPlus()'
But I cannot make that function static, otherwise I cannot access to _myvar anymore.
The examples are not useful because they put everything outside any class and it's against any basic rule of programming.
Second question. In my menu I have dozens of int vars to set.
I really don't want to create a lot of functions to increase or decrease each single var!
How to retrieve, inside editIntPlus(), the current var being edited? The goal is to attach the same function to all the vars.
I saw this answer but:
I cannot declare
editIntPlusasfriend:friend: void editIntPlus();
leads to:
include/menu.h:82:5: error: expected primary-expression before 'void'
void editIntPlus();
^~~~
- as said before, I don't want to make my function
staticotherwise I cannot access anymore to the class members
Solution 1:[1]
Following the suggestion of user17732522 I forked the library making these changes:
LiquidMenu.h
void (*_function[MAX_FUNCTIONS])(void *); ///< Pointers to the functions
void (*_context[MAX_FUNCTIONS]); ///< Pointers to the contexts
LiquidLine.cpp
bool LiquidLine::attach_function(uint8_t number, void (*function)(void *), void* context) {
...
_context[number - 1] = context;
...
(*_function[number - 1])(_context[number - 1]);
and in my code (corrected after user17732522 suggestion):
void editIntPlus(void *context);
line2_setupCC1.attach_function(1, [](void* context){ static_cast<Menu*>(context)->editIntPlus(context); }, this);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
