CodePlea icon
Random thoughts on programming

PlusCallback Usage Summary

This page describes basic usage, examples, and tips for using PlusCallback, the C++ callback library.

Basic Usage

Step 1 - Include the library

The entire library is self-contained in one file. To use it in your project, you only need to include it.

#include <callback.hpp>

Step 2 - Have some things to call

You'll need something to call. It'll probably be some complicated object, or maybe just a function.

struct Dog
    void Bark(int volume);

struct Cat
    void Meow(int volume);

Dog spot, rover; //We have two dogs
Cat felix; //and one cat.

//Define a normal function.
void Func(int a);

Step 3 - Use a callback

The PlusCallback library is contained in the namespace cb. The class for implementing callbacks is called CallbackX, where X is the number of parameters the callback function takes. This class is templated, and the template parameters are the function return type, followed by each parameter's type.

    //Define a callback to a function returning void and taking
    //one int parameter.
    cb::Callback1<void, int> speak;

    //Point this callback at spot's Bark method.
    speak.Reset(&spot, &Dog::Bark);
    speak(50); //Spot barks loudly.

    speak.Reset(&rover, &Dog::Bark);
    speak(60); //Rovers lets out a mighty bark.

    speak.Reset(&felix, &Cat::Meow);
    speak(30); //Felix meows.

Step 4 (Optional) - Get fancy

PlusCallback defines flexible, robust objects. Go ahead and copy them, reset them, and put them in containers. That's what they're there for.

    //Callbacks can be set to free functions.
    speak = Func;

    //Copy and assignment operators are well defined.
    cb::Callback1<void, int> copy = speak;
    assert(copy == speak);

    //Callbacks can be set to null.

    //Callbacks are container safe with a well defined sort order.
    std::set<cb::Callback1<void, int> > container;

    //Use the helper function MakeX to quickly create callback objects.
    container.insert(cb::Make1(&spot, &Dog::Bark));
    container.insert(cb::Make1(&rover, &Dog::Bark));
    container.insert(cb::Make1(&felix, &Cat::Meow));