I think that some newer languages like JS can do this natively, but I forget the term for it (make a “temporary” function in-line just to pass as a callback)
What I want to do is …
I’m writing unit tests where I set up expected input & output messages at compile time. Later at run time, I want to do some checks when each output is received or input has been processed, so I added a parameter for a callback function.
That’s working fine and I could leave it & move on, but … I am just curious …
sometimes a function is overkill and I just need a single comparison; sometime a small block of code would do. Perhaps I could just evaluate these to a zero/non-zero value at run time? But how to pass as a parameter?
At the moment my function has the following signature
void AddExpectedCommand(E_peripheralType peripheral,
communicationBlock_t commandBlock,
errorMessage_t errorMessage,
void *(*DoRunTimeChecks)(E_boolean));
where the final parameter is pointer to a callback function returning boolean.
Is there any way that I could pass a code expression as a parameter instead?
Or does a function seem “cleaner”?
Thanks in advance for any help …
Update: oops, I got my declaration wrong. I want to pass a pointer so a function which has no parameters and returns an e_Boolean … how do I do that?
With C++11 you can do the following:
Function taking a function that returns a bool:
Call it with a lambda capturing a local variable:
Or call it with some function g that returns a bool:
Or bind some function h that takes an int and returns a bool: