Click here to Skip to main content
15,896,154 members
Articles / Programming Languages / C++

Fast C++ Delegate: Boost.Function 'drop-in' replacement and multicast

Rate me:
Please Sign up or sign in to vote.
4.86/5 (51 votes)
1 Jun 200733 min read 292.9K   1.9K   110  
An article on the implementation of a fast C++ delegate with many advanced features.
// FD.Delegate Library

//  Copyright Douglas Gregor 2004.
//  Copyright 2005 Peter Dimov

//  Use, modification and distribution is subject to
//  the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

// Copyright (C) 2007 JaeWook Choi
// , modified from Boost.Function contains2_test.cpp

#include <fd/delegate.hpp>
#include <boost/detail/lightweight_test.hpp>

static int forty_two()
{
    return 42;
}

struct Seventeen
{
    int operator()() const
    {
        return 17;
    }
};

bool operator==(const Seventeen&, const Seventeen&)
{
    return true;
}

struct ReturnInt
{
    explicit ReturnInt(int value) : value(value)
    {
    }

    int operator()() const
    {
        return value;
    }

    int value;
};

bool operator==(const ReturnInt& x, const ReturnInt& y)
{
    return x.value == y.value;
}

bool operator!=(const ReturnInt& x, const ReturnInt& y)
{
    return x.value != y.value;
}

int main()
{
    fd::delegate0<int> fn;

    fn = &forty_two;

    BOOST_TEST( fn() == 42 );

    BOOST_TEST( fn.contains(&forty_two) );
    BOOST_TEST( !fn.contains( Seventeen() ) );
    BOOST_TEST( !fn.contains( ReturnInt(0) ) );
    BOOST_TEST( !fn.contains( ReturnInt(12) ) );

    fn = Seventeen();

    BOOST_TEST( fn() == 17 );

    BOOST_TEST( !fn.contains( &forty_two ) );
    BOOST_TEST( fn.contains( Seventeen() ) );
    BOOST_TEST( !fn.contains( ReturnInt(0) ) );
    BOOST_TEST( !fn.contains( ReturnInt(12) ) );

    fn = ReturnInt(12);

    BOOST_TEST( fn() == 12 );

    BOOST_TEST( !fn.contains( &forty_two ) );
    BOOST_TEST( !fn.contains( Seventeen() ) );
    BOOST_TEST( !fn.contains( ReturnInt(0) ) );
    BOOST_TEST( fn.contains( ReturnInt(12) ) );

    return boost::report_errors();
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Other
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions