logoalt Hacker News

_randyr06/15/20253 repliesview on HN

I'm not a C++ programmer, but I was under the impression that closures in c++ were just classes that overload the function call operator `operator()`. So each closure could also be implemented as a named class. Something like:

    class OnListItemSelected {
        OnListItemSelectedData data;

        void operator()(int selectedIndex) { ... }
    }
Perhaps I'm mistaken in what the author is trying to accomplish though?

Replies

OskarS06/15/2025

Indeed, that is exactly the case, lambdas are essentially syntax sugar for doing this.

The one thing the author's solution does which this solution (and lambdas) does not is type erasure: if you want to pass that closure around, you have to use templates, and you can't store different lambdas in the same data structure even if they have the same signature.

You could solve that in your case by making `void operator()` virtual and inheriting (though that means you have to heap-allocate all your lambdas), or use `std::function<>`, which is a generic solution to this problem (which may or may not allocate, if the lambda is small enough, it's usually optimized to be stored inline).

I get where the author is coming from, but this seems very much like an inferior solution to just using `std::function<>`.

show 2 replies
spacechild106/15/2025

Exactly! And if you need type erasure, you can just store it in a std::function.

> OnListItemSelectedData data;

In this case you can just store the data as member variables. No need for defining an extra class just for the data.

As I've written elsewhere, you can also just use a lambda and forward the captures and arguments to a (member) function. Or if you're old-school, use std::bind.

InfiniteRand06/15/2025

Main issue author had with lambdas is autogenerated names in crash reports

show 1 reply