C++ Delegates

07 Jun 2019 - Simon Coenen - Reading time: 12 mins

I’ve always really liked working with delegates in Unreal Engine 4. It’s so easy to use, works in various different ways and after a while of using them, I wanted to try to implement them myself. As you might know, it’s not straight forward at all to store and execute a method in a generic way in C++. A function pointer might be a solution but it’s not flexible as it’s very type-restricted and can’t have any extra data a lambda would have. The standard template library solved this by providing std::function<> which is sort of a more flexible and fancy function pointer. However, I’ve found that both function pointers and std::function are such a headache to work with!.

Take a look at an extremely simple example of executing a member function with a int(float) signature. Straight forward right? Well, not really…

Foo foo;

// Function pointer. Arrrghh
int(Foo::* pFunctionA)(float) = &Foo::Bar;
(foo.*pFunctionA)(42);

// std::function. Object itself passed as variable (makes kind of sense but extremely awkward!)
std::function<int(Foo&, float)> pFunctionB = &Foo::Bar;
pFunctionB(foo, 42);

// Delegate. Elegant and straight forward
auto pFunctionC = Delegate<int, float>::CreateRaw(&foo, &Foo::Bar);
pFunctionC.Execute(42);

Read More...


A blog...?

06 Jun 2019 - Simon Coenen - Reading time: 1 min

I really like programming blogs and I love reading about how people learn from personal projects and share their thinking process, ideas and potentially implementation details. Just to name a few of many blogs in my bookmarks bar that are absolutely worth checking out:

There are loads of interesting blogs I check out once in a while but I always though making one myself wouldn’t be very interesting because many of the things I could write about are already touched upon many many times in other places and I don’t really feel like I could be committed to maintain it.

However, I’ve been working on a personal game engine and loads of other little projects and other things for a while now but I could never think of a way to present this in a good form to others because those things will never be “finished”. That’s why I thought a blog could be a great way to pick a few interesting things I’ve done and write about it. Besides, implementing something is one thing but by writing about it, you have to comprehend the subject much better as there will be gaps of information that will force me to research more.

I’m hoping for this to be a good little exercise moving forward. If there’s anything you don’t agree with, like to comment on or if you just like to reach out to me, always feel free to reach out to me on Twitter, email or comment below.

Read More...