Greg Hewgill (ghewgill) wrote,
Greg Hewgill
ghewgill

delegates in C++

Today I came across a fantastic article titled Member Function Pointers and the Fastest Possible C++ Delegates. This article describes in detail the implementation of the little-used C++ feature of member function pointers, then leverages certain necessary properties of the implementation to provide a really nice way of doing "delegates" in C++. Delegates will be familiar to those who have some experience with C#.

Member function pointers provide only a thin enhancement to regular function pointers. In some ways they are even less convenient because to make use of them, you also need to carry around an object pointer through which to call the member function. (And, their syntax is horrid.) Delegates bind together an object pointer and a member function into one callable object. In this way, you can avoid having to declare a static non-member function to be used as a callback function, which then picks up an object pointer from somewhere, usually an opaque parameter or a global (ugh), and calls a corresponding member function, which does the real work. Using delegates, you just make a delegate containing both the object pointer and the member function pointer, and pass that to the framework which calls back to your member function transparently.

Anyway, the article does a much better job of explaining this than I have. Be warned, though—it's long, and goes into excruciating detail, so it's probably only recommended for hard-core C++ programmers. But, the end result is very elegant and useful.

Note that the downloads on the article are sequestered behind a login. I've already logged in and downloaded the code, and since it's public domain, I've put a copy on my own server without any login required, for your convenience.

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments