Skip to content

boost::lambda: using std::sqrt and std::exp inside boost::lambda expression

In a nutshell, boost::lambda

The Boost Lambda Library (BLL in the sequel) is a C++ template library, which implements a form of lambda abstractions for C++. The term originates from functional programming and lambda calculus, where a lambda abstraction defines an unnamed function. The primary motivation for the BLL is to provide flexible and convenient means to define unnamed function objects for STL algorithms. In explaining what the library is about, a line of code says more than a thousand words; the following line outputs the elements of some STL container a separated by spaces:

for_each(a.begin(), a.end(), std::cout << _1 << ' ');


Bind a target function with arg-list

boost::lambda::bind(func, arg-list);

Bind a target class member with object and arg-list

boost::lambda::bind(a-class-member, object, arg-list);

std::sqrt and std::exp inside boost::lambda expression

using standard lambda: boost::lambda binds standard lambda.

boost::lambda::bind([] (auto x) {return std::sqrt<double>(x).real();}, _1)

boost::lambda::bind([] (auto x) {return std::exp<double>(x).real();}, _1)

Full c++ Example Code

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <complex>
#include <iostream>
#include <algorithm>
#include <vector>

namespace ld = boost::lambda;
using ld::_1;

int main()
        std::vector<double> vector{2,3,5,7,11,13,17,19};
        std::copy(vector.begin(), vector.end(),
                std::ostream_iterator<double>(std::cout, " "));
        std::cout << std::endl;

        // boost::lambda binds a standard lambda.
                        [] (auto x) {
                                return std::sqrt<double>(x).real();

        for (auto & value: vector) std::cout << value << ' ';
        std::cout << std::endl;

        (std::cout << ld::bind([] (auto x) {
                return std::sqrt<double>(x);
        }, _1) << '\n' << ld::bind([] (auto x) {
                return std::exp<double>(x);
        }, _1) << '\n')(





No Trackbacks


Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.

Form options

Submitted comments will be subject to moderation before being displayed.