Boost C++ Libraries Home Libraries People FAQ More

Next

Chapter 1. Boost.Functional/OverloadedFunction 1.0.0

Lorenzo Caminiti

Distributed under 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)

Table of Contents

Introduction
Getting Started
Compilers and Platforms
Installation
Tutorial
Overloading
Without Function Types
Reference
Header <boost/functional/overloaded_function.hpp>
Header <boost/functional/overloaded_function/config.hpp>
Acknowledgments

This library allows to overload different functions into a single function object.

Consider the following functions with distinct signatures:

const std::string& identity_s(const std::string& x) { return x; } // As pointer.

int identity_i_impl(int x) { return x; }
int (&identity_i)(int) = identity_i_impl; // Function reference.

double identity_d_impl(double x) { return x; }
boost::function<double (double)> identity_d = identity_d_impl; // Functor.

Instead of calling them using their separate names (here BOOST_CHECK is equivalent to assert): [1]

BOOST_CHECK( identity_s("abc") == "abc" );
BOOST_CHECK( identity_i(123) == 123 );
BOOST_CHECK( identity_d(1.23) == 1.23 );

It is possible to use this library to create a single overloaded function object (or functor) named identity that aggregates together the calls to the specific functions (see also identity.cpp):

boost::overloaded_function<
      const std::string& (const std::string&)
    , int (int)
    , double (double)
> identity(identity_s, identity_i, identity_d);

// All calls via single `identity` function.
BOOST_CHECK( identity("abc") == "abc" );
BOOST_CHECK( identity(123) == 123 );
BOOST_CHECK( identity(1.23) == 1.23 );

Note how the functions are called via a single overloaded function object identity instead of using their different names identity_s, identity_i, and identity_d.



[1] In the examples presented in this documentation, BOOST_CHECK is used instead of assert because it allows to write regression tests using Boost.Test. The examples of this documentation are executed as part of the library test suite to verify that they always compile and run correctly.

Last revised: February 14, 2012 at 16:16:51 GMT


Next