C ++ code as an argument

I have this code:

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

mostly:

  GpsLon.onUpdate(longitudeChanged); 

I would like to do something like this:

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

(As in Java script!); but this is far from the case. How to do it?

Tpx

Eric

+5
source share
1 answer

Here, the mighty lambda!

 #include <iostream> template <typename T> void myFunction(T t) { t(); } int main() { myFunction([](){ std::cout << "Hi!" << std::endl; }); } 

If you want to know more about them, look here.

To decrypt this a bit, here is a breakdown:

  • You have a function that takes another function through a template argument.
  • This function does nothing but call its argument.
  • Inside main, you call this function with a lambda as an argument.
  • The lambda can be divided into three parts [] (capture, do not worry about it for too long) () arguments of the function, in this case they are not) and { ... } (the body, like any other function).

So the lambda part is simple:

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

Here is another lambda example that takes an int and returns double its value:

 [](int value){ return value * 2; } 
+8
source

All Articles