Diggins PDP #2 : Meta-Binders (binding functions to functions)

  • Thread starter christopher diggins
  • Start date
C

christopher diggins

// meta_binder.hpp
// The Diggins PDP (Public Domain Post) #2
// Public Domain code by Christopher Diggins, May 22, 2005
//
// Description:
// A meta-binder binds function objects to function objects
//
// Motivation:
// lack of a logical_xor in the standard library, and no way to construct
one using the
// standard library using binders and adapters.

#ifndef META_BINDER_HPP
#define META_BINDER_HPP

#include <stdexcept>
#include <functional>

namespace cdiggins
{
template<class BinOp, class BinOpArg1, class BinOpArg2>
class meta_binder2 : public std::binary_function
<
typename BinOp::first_argument_type,
typename BinOp::second_argument_type,
typename BinOp::result_type{
protected:
BinOp op;
BinOpArg1 arg1;
BinOpArg2 arg2;
public:
meta_binder2(BinOp x, BinOpArg1 a1, BinOpArg2 a2) : op(x), arg1(a1),
arg2(a2)
{ }
typename BinOp::result_type operator()
(const typename BinOp::first_argument_type& x,
const typename BinOp::second_argument_type& y)
{
return op(arg1(x, y), arg2(x, y));
}
};

template<class BinOp, class BinOpArg1, class BinOpArg2>
meta_binder2<BinOp, BinOpArg1, BinOpArg2>
meta_bind2(BinOp op, BinOpArg1 arg1, BinOpArg2 arg2) {
return meta_binder2<BinOp, BinOpArg1, BinOpArg2>(op, arg1, arg2);
}
}

void test(bool b) {
if (!b)
throw std::runtime_error("test failed");
}

namespace meta_binder_test
{
using namespace cdiggins;

bool logical_xor(bool x, bool y) {
return (x || y) && !(x && y);
}

void xor_test(bool x, bool y) {
test(logical_xor(x, y) ==
meta_bind2(
std::logical_and<bool>(),
std::logical_or<bool>(),
std::not2(std::logical_and<bool>())
)(x, y));
}

void test_main()
{
xor_test(true, true);
xor_test(true, false);
xor_test(false, true);
xor_test(false, false);
}
}

#endif
 
R

Rapscallion

christopher said:
// meta_binder.hpp
// The Diggins PDP (Public Domain Post) #2
// Public Domain code by Christopher Diggins, May 22, 2005
//
// Description:
// A meta-binder binds function objects to function objects
//
// Motivation:
// lack of a logical_xor in the standard library, and no way to construct
one using the
// standard library using binders and adapters.

Did it ever occur to you that normal C++ programmers may be reluctant
to write something like:

logical_xor(x, y) ==
meta_bind2(
std::logical_and<bool>(),
std::logical_or<bool>(),
std::not2(std::logical_and<boo­l>())
)(x, y);
?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top