2

Can I use boost::bind or the boost lambda library to create a functor that ignores its arguments and always returns a constant?

e.g. a functor with equivalent behaviour to:

int returnThree( SomeType arg ) { return 3; }
SimonD
  • 638
  • 5
  • 16

2 Answers2

2

Sure, use

boost::phoenix::val(3);

See it Live On Coliru

#include <boost/phoenix.hpp>

namespace p = boost::phoenix;
using namespace p::arg_names;

int main()
{
    auto p = p::val(42);
    return p() + p(/*ignored:*/77);
}

Which returns 84 as the exitcode.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    Even gives you up to 10 arguments, whereas `boost::lambda::constant` limits you to 3. – Barry Oct 28 '14 at 15:13
1

From Barry's comment on sehe's answer:

#include "boost/lambda/lambda.hpp"

...

auto returnThree = boost::lambda::constant(3);
SimonD
  • 638
  • 5
  • 16