Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Code in function as argument

I have this code:

void longitudeChanged() {
  Serial.println("Longitude: " + String(GpsLon.value,8));
}

in main:

  GpsLon.onUpdate(longitudeChanged);

I would like to do something like this:

GpsLon.onUpdate({
  Serial.println("Longitude: " + String(GpsLon.value,8));
});

(Like I do in Java script!); but this is not the rigth way. How to do it?

Tnx

Erik

like image 748
Erik P Avatar asked Sep 06 '16 16:09

Erik P


People also ask

Can a function be an argument in C?

Till now, we have seen that in C programming, we can pass the variables as an argument to a function. We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

How do you pass a function as an argument?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

What is argument in C with example?

The values that are declared within a function when the function is called are known as an argument. These values are considered as the root of the function that needs the arguments while execution, and it is also known as Actual arguments or Actual Parameters.

What is the syntax for a function with arguments?

When one piece of code invokes or calls a function, it is done by the following syntax: variable = function_name ( args, ...); The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.


1 Answers

Behold, the mighty lambda!

#include <iostream>

template <typename T>
void myFunction(T t) {
    t();
}

int main() {
    myFunction([](){ std::cout << "Hi!" << std::endl; });
}

If you'd like to learn more about them, take a look here

To decrypt this a little, here's a breakdown:

  • You have a function that takes another function via a template argument.
  • That function does nothing other than call its argument.
  • Inside of main, you call that function with a lambda as its argument.
  • The lambda can be broken into three parts [] (the capture, don't worry too much about that for now) () the function arguments, in this case there are none) and { ... } (the body, just like any other function).

So the lambda part is just this:

[](){ std::cout << "Hi!" << std::endl; }

Here's another example of a lambda that takes an int and returns double its value:

[](int value){ return value * 2; }
like image 189
OMGtechy Avatar answered Sep 19 '22 22:09

OMGtechy