There is a structure of function pointers:

typedef struct { int (*pfnVidInit)(); .... } UI_FUNCTIONS; 

I need to create and fill an instance of this structure. In C, I simply entered the names of the functions:

 static UI_FUNCTIONS gMenuFuncs = { Menu_VideoInit, ... }; 

Now I decided to try to change my menu in C ++:

 static UI_FUNCTIONS gMenuFuncs = { Menu::getInstance()->VideoInit, ... }; 

But the compiler writes that it cannot cast int (Menu::)() (Menu::) int (Menu::)() to int (*)() Why is it there (Menu::) , but not (*) and how can I do (*) ?

  • 2
    Because it is a class method, and this method should be called on the object, and not just as a free function. - ixSci
  • What should I do then, vrapper? - Vitaly Karpenko
  • Show more code what VideoInit , for example - ixSci
  • int (void) function: int Menu::VideoInit() - Vitaly Karpenko
  • one
    A function VideoInit can not be made static and not suffer? If not, then, you see, this function actually takes an additional parameter - a pointer to a class object ... So you can't call it as an int() . In my opinion, it is better to write a wrapper ... - Harry

1 answer 1

Do this:

 struct UiFunctions { std::function<int()> VidInit; .... }; static UiFunctions gMenuFuncs = { []{return Menu::getInstance()->VideoInit();}, ... }; 

Do not forget to connect functional . I don’t like the code anyway, but it is as close as possible to your version.

You may have to wrap the lambda in std::function , since in this context, conversion may not work. In this case, you should write this:

 static UiFunctions gMenuFuncs = { std::function<int()>([]{return Menu::getInstance()->VideoInit();}), ... }; 

PS Yes, it would be possible to leave a pointer to a function, but I did not do that, because, all other things being equal, the variant with std::function more universal and idiomatic, in modern C ++.