C++ Academy · Lesson

Choosing Callables

Lambdas vs bind vs pointers.

Lesson 4 of 413 steps

Choosing Callables is a free C++ Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

The Callable Toolbox

C++ offers several ways to pass behavior around: function pointers, lambdas, functors, std::bind, and std::function. Each fits different needs.

  • Speed vs flexibility is the usual tradeoff.
  • Readability matters too.
#include <iostream>

int twice(int x) { return x * 2; }

int main() {
    int (*fp)(int) = twice;
    auto lam = [](int x) { return x * 2; };
    std::cout << fp(5) << ' ' << lam(5) << '\n';
    return 0;
}

When to Use a Function Pointer

Reach for a function pointer when you need a tiny, stateless callback and want C compatibility or zero overhead.

#include <iostream>

void logMsg(const char* m) { std::cout << "LOG: " << m << '\n'; }

int main() {
    void (*handler)(const char*) = logMsg;
    handler("started");
    return 0;
}

When to Use a Lambda

A lambda is the default modern choice: concise, can capture state, and the compiler inlines it well in templates and algorithms.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5};
    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
    return 0;
}

Capturing State in a Lambda

Lambdas capture surrounding variables, something function pointers cannot do, making them ideal for context-aware callbacks.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    int threshold = 3;
    std::vector<int> v = {1, 2, 3, 4, 5};
    int c = std::count_if(v.begin(), v.end(), [threshold](int x) { return x > threshold; });
    std::cout << c << '\n';
    return 0;
}

When to Use a Functor

A functor (struct with operator()) suits a reusable, named operation that may hold configuration and be used in many places.

#include <iostream>
#include <vector>
#include <algorithm>

struct AboveThreshold {
    int limit;
    bool operator()(int x) const { return x > limit; }
};

int main() {
    std::vector<int> v = {1, 5, 2, 8};
    std::cout << std::count_if(v.begin(), v.end(), AboveThreshold{4}) << '\n';
    return 0;
}

Lambda vs bind

Both can pre-fill arguments. The lambda version is usually clearer and easier for the compiler to optimize, so prefer it over std::bind.

#include <iostream>

int power(int base, int exp) {
    int r = 1;
    for (int i = 0; i < exp; ++i) r *= base;
    return r;
}

int main() {
    auto square = [](int x) { return power(x, 2); };
    std::cout << square(6) << '\n';
    return 0;
}

When to Use std::function

Use std::function when you must store a callable of unknown concrete type, for example in a class member or a container.

#include <iostream>
#include <functional>
#include <vector>

int main() {
    std::vector<std::function<int(int)>> pipeline;
    pipeline.push_back([](int x) { return x + 1; });
    pipeline.push_back([](int x) { return x * 3; });
    int v = 2;
    for (auto& f : pipeline) v = f(v);
    std::cout << v << '\n';
    return 0;
}

Templates Avoid Overhead

If a function only needs to receive a callable (not store it), a template parameter keeps full speed by avoiding type erasure.

#include <iostream>

template <typename F>
int applyTwice(int x, F f) { return f(f(x)); }

int main() {
    std::cout << applyTwice(3, [](int n) { return n + 10; }) << '\n';
    return 0;
}

Performance Ranking

Roughly: a templated callable or capture-less lambda is fastest, a function pointer is close, and std::function is slowest due to indirection and possible allocation.

#include <iostream>
#include <functional>

int main() {
    auto fast = [](int x) { return x + 1; };
    std::function<int(int)> flexible = fast;
    std::cout << fast(1) << ' ' << flexible(1) << '\n';
    return 0;
}

A Decision Guide

Quick guide:

  • Need to store any callable? std::function.
  • Just receiving one in a generic function? template parameter.
  • Inline behavior with state? lambda.
  • C API or stateless? function pointer.
#include <iostream>
#include <functional>

void runStored(const std::function<void()>& cb) { cb(); }

template <typename F>
void runGeneric(F f) { f(); }

int main() {
    runStored([] { std::cout << "stored\n"; });
    runGeneric([] { std::cout << "generic\n"; });
    return 0;
}

Putting It All Together

A small event system might receive handlers generically but store them in std::function so they can be invoked later.

#include <iostream>
#include <functional>
#include <vector>

struct Dispatcher {
    std::vector<std::function<void(int)>> handlers;
    template <typename F> void on(F f) { handlers.emplace_back(f); }
    void fire(int e) { for (auto& h : handlers) h(e); }
};

int main() {
    Dispatcher d;
    d.on([](int e) { std::cout << "got " << e << '\n'; });
    d.fire(7);
    return 0;
}

Quick Check

Test your understanding of choosing callables.

Recap

You learned how to choose a callable:

  • function pointer for stateless, C-compatible callbacks
  • lambda as the default for inline, stateful behavior
  • functor for reusable named operations
  • template parameter when only receiving a callable (fastest)
  • std::function when you must store one of unknown type

That completes the Function Objects and std::bind course.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Choosing Callables” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Choosing Callables”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Choosing Callables”?

Lambdas vs bind vs pointers. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Choosing Callables” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Function Pointers
  2. std::function
  3. std::bind
  4. Choosing Callables
← Back to C++ Academy