Chicago C/C++ Users Group Message Board › Object-Oriented Design Patterns for Computation

Object-Oriented Design Patterns for Computation

Nevin ".
nliber
Libertyville, IL
Post #: 53
Here is my solution for the additive pattern without macros in the interface (except for the include guards). It uses CRTP (Curiously Recurring Template Pattern) and Boost.Operators to remove some of the drudge work:


#ifndef AdditivePatternStuff_AdditivePattern_h
#define AdditivePatternStuff_AdditivePattern_h

#include <boost/operators.hpp>
#include <ostream>

template<typename T, typename V>
class AdditivePattern
: boost::totally_ordered<T
, boost::additive<T
, boost::multiplicative<T, V
> > >
{
protected:
AdditivePattern() : value() {}
explicit AdditivePattern(V const& v) : value(v) {}


friend bool operator==(T const& lhs, T const& rhs)
{ return lhs.value == rhs.value; }

friend bool operator<(T const& lhs, T const& rhs)
{ return lhs.value < rhs.value; }


friend T& operator+=(T& lhs, T const& rhs)
{ lhs.value += rhs.value; return lhs; }

friend T& operator-=(T& lhs, T const& rhs)
{ lhs.value -= rhs.value; return lhs; }


friend T& operator*=(T& lhs, V const& v)
{ lhs.value *= v; return lhs; }

friend T& operator/=(T& lhs, V const& v)
{ lhs.value /= v; return lhs; }


friend std::ostream& operator<<(std::ostream& os, T const& that)
{ return os << that.value; }


V value;
};


#endif /* AdditivePatternStuff_AdditivePattern_h */


And here is how you use it:


#include "AdditivePattern.h"
#include <iostream>

struct MyType : AdditivePattern<MyType, int>
{
MyType() {}
explicit MyType(int i) : AdditivePattern<MyType, int>(i) {}
};

int main()
{
MyType a(2);
MyType b(3);

std::cout << "a==" << a << std::endl;
std::cout << "b==" << b << std::endl;

std::cout << "(a!=b)==" << (a != b) << std::endl;
std::cout << "(a>=b)==" << (a >= b) << std::endl;

std::cout << "a+b==" << (a + b) << std::endl;
std::cout << "a-b==" << (a - b) << std::endl;

std::cout << "5*a==" << (5 * a) << std::endl;
std::cout << "a/7==" << (a / 7) << std::endl;

return 0;
}


Enjoy!
Nevin :-)
Powered by mvnForum

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy