Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

C++ Programming

design pattern for defining a relational operator


I want the DataAnDRelation is flexible in design so that client code
can define its own relationship according to their own needs.

I am trying to use function pointer, but that needs client code to
declare friendship in the class DataAndRelation, which I feel not
neat. Any design pattern/standard way to solve this problem.

bool MyRelation(double a, double b) {
  return a > b;

}

bool MyRelationABS(double a, double b) {
  return abs(a) > abs(b);

}

class DataAndRelation {
 public:
  DataAndRelation (double a, bool (*ptr )(double, double) ) { data =
a; ptr_relation = ptr; }
  ~DataAndRelation () {}
  bool GreatOrEaqual (const DataAndRelation& other) const {
     return (*ptr_relation) (this->data, other.data);
  }
 private:
  double data;
  bool (*ptr_relation )(double, double);

}

int main() {
  DataAndRelation example(1.0, MyRelation);
  DataAndRelation example2(2.0, MyRelationABS);
  ...
  ...

On Jun 5, 5:31 am, newbie <mitbb@yahoo.com> wrote:

Very good. Thank you.

"newbie" <mitbb@yahoo.com> wrote in message

news:1180992714.345351.189170@x35g2000prf.googlegroups.com...

What about something like this?  Basically I've replaced function pointers
with real objects or functors.
This is based upon some pattern, "strategy" perhaps ?

dave

#include "math.h"

class Relation
{
public:
 virtual bool compare( double a, double b) const = 0;
 virtual ~Relation();

};

class LessThan : public Relation
{
public:
  virtual bool compare( double a, double b) const
  {
   return a < b;
  }
};

class LessAbs : public Relation
{
public:
  virtual bool compare( double a, double b) const
  {
   return  fabs(a) <  fabs(b);
  }

};

class DataAndRelation
{
 public:
  DataAndRelation (double a, Relation* relation )
   :_data(a), _relation(relation)
  {
  }
   bool GreatOrEaqual (const DataAndRelation& other) const
   {

     return _relation->compare( _data, other.data() );
   }
   double data() const { return _data ;}

 private:
  double _data;
  Relation* _relation;

};

int main()
{
  LessThan lessThan;
  LessAbs lessAbs;
  DataAndRelation example(1.0, &lessThan);
  DataAndRelation example2(2.0, &lessAbs);

  return 0;

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc