CodeTheRobot

C++ Intermediate · Lesson 13 of 27

std::function

Storing any callable, callback members and the cost of type erasure.

Estimated time · 45–60 min

Learning goals

What you will understand

  • Explain std::function in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

std::function<R(Args...)> can hold any callable with that signature: a free function, a lambda or a functor. This lets a class store a callback without knowing its exact type, which is how event-driven code and many ROS 2 APIs work.

std::function has a small cost (indirect call, sometimes an allocation). Use a template parameter for hot code, and std::function for stored callbacks. Check an empty function with if (callback) before calling, since calling an empty one throws.

Guided lesson

Work through these steps

  1. 1.

    Read the std::function example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include <functional>
// Header for std::function.
class Button {
// A class that reports events through a callback.
public:
// Public interface.
  using Callback = std::function<void(int)>;
// Any callable taking an int and returning nothing.
  void on_press(Callback cb) { cb_ = std::move(cb); }
// Store the callback, moving it to avoid a copy.
  void press(int id) { if (cb_) cb_(id); }
// Call it, but only if one was set.
private:
// Hidden data.
  Callback cb_;
// Empty until set.
};
// End of the class.
Button b;
// Create a button with no callback.
b.on_press([](int id) { std::cout << "button " << id << '\n'; });
// Register a lambda.
b.press(7);
// Triggers the callback: prints 'button 7'.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for std::function. Expected result: button 7

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <functional>
#include <iostream>

class Button {
 public:
  using Callback = std::function<void(int)>;
  // TODO: store the callback in on_press(); call it in press() only if one was set

 private:
  Callback cb_;
};

int main() {
  Button b;
  b.on_press([](int id) { std::cout << "button " << id << '\n'; });
  b.press(7);
  return 0;
}

Expected output

button 7
Stuck? Show the full solution (try it yourself first)
#include <functional>
#include <iostream>

class Button {
 public:
  using Callback = std::function<void(int)>;
  void on_press(Callback cb) { cb_ = std::move(cb); }
  void press(int id) {
    if (cb_) cb_(id);
  }

 private:
  Callback cb_;
};

int main() {
  Button b;
  b.on_press([](int id) { std::cout << "button " << id << '\n'; });
  b.press(7);
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Write an EventBus with register(std::function<void(const std::string&)>) that stores several callbacks and calls them all in publish(). Register a lambda and a free function and test both.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.