Click here to Skip to main content
13,048,584 members (87,285 online)
Click here to Skip to main content

Tagged as

Stats

65.5K views
1.8K downloads
128 bookmarked
Posted 15 Dec 2010

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

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

using util::Callback;

class Foo
{
public:
    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)
{
    if(callback)
    {
        ::printf("%f\n", callback(a, b));
    }
    else
    {
        ::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:
        30.000000
        -10.000000
        200.000000
        0.500000
        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.

License

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

Share

About the Author

Elbert Mai
United States United States
No Biography provided

You may also be interested in...

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