Click here to Skip to main content
11,703,940 members (68,248 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Lightweight Generic C++ Callbacks (or, Yet Another Delegate Implementation)

, 15 Dec 2010 CPOL 104.8K 1.6K 124
A fast, standards-compliant, and easy-to-use C++ callback implementation
#include <cstdio>
#include "callback.hpp"

using util::Callback;

class Foo
    Foo() {}
    double MemberFunction(int a, int b)            { return a+b; }
    double ConstMemberFunction(int a, int b) const { return a-b; }
    static double StaticFunction(int a, int b)     { return a*b; }

double GlobalFunction(int a, int b) { return a/(double)b; }

void Invoke(int a, int b, Callback<double (int, int)> callback)
        ::printf("%f\n", callback(a, b));
        ::printf("Nothing to call.\n");

int main()
    Foo f;
    Invoke(10, 20, BIND_MEM_CB(&Foo::MemberFunction, &f));
    Invoke(10, 20, BIND_MEM_CB(&Foo::ConstMemberFunction, &f));
    Invoke(10, 20, BIND_FREE_CB(&Foo::StaticFunction));

    Callback<double (int, int)> cb = BIND_FREE_CB(&GlobalFunction);
    Invoke(10, 20, cb);

    cb = util::NullCallback();
    Invoke(10, 20, cb);

    /* Expected output:
        Nothing to call.

    return 0;

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Elbert Mai
United States United States
No Biography provided

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150819.1 | Last Updated 15 Dec 2010
Article Copyright 2010 by Elbert Mai
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid