c++: lazy evaluation
#include <vector>
#include <assert.h>
struct Expression;
struct Num
{
Num(size_t n, int i)
{
data.resize(n, i);
}
Num& operator=(Expression& exp);
void print() const
{
for(size_t i=0; i<data.size();i++)
printf("%d ", data);
printf("\n");
}
std::vector <int> data;
};
struct Expression
{
Expression(Num const & a,
Num const & b)
:a_(a), b_(b)
{
assert(a_.data.size()==b_.data.size());
}
void apply(Num *p)
{
size_t n=a_.data.size();
if(p->data.size()!= n)
p->data.resize(n);
for(size_t i=0; i<n;i++)
p->data[i] = a_.data[i] + b_.data[i];
}
Num const & a_;
Num const & b_;
};
Num& Num::operator=(Expression& exp)
{
exp.apply(this);
return *this;
}
Expression operator+(Num const & a,Num const & b)
{
return Expression(a,b);
}
void main()
{
Num a(10, 1);
Num b(10, 10);
Num c(0, 0);
c = Expression(a+b);
c.print();
}
#include <assert.h>
struct Expression;
struct Num
{
Num(size_t n, int i)
{
data.resize(n, i);
}
Num& operator=(Expression& exp);
void print() const
{
for(size_t i=0; i<data.size();i++)
printf("%d ", data);
printf("\n");
}
std::vector <int> data;
};
struct Expression
{
Expression(Num const & a,
Num const & b)
:a_(a), b_(b)
{
assert(a_.data.size()==b_.data.size());
}
void apply(Num *p)
{
size_t n=a_.data.size();
if(p->data.size()!= n)
p->data.resize(n);
for(size_t i=0; i<n;i++)
p->data[i] = a_.data[i] + b_.data[i];
}
Num const & a_;
Num const & b_;
};
Num& Num::operator=(Expression& exp)
{
exp.apply(this);
return *this;
}
Expression operator+(Num const & a,Num const & b)
{
return Expression(a,b);
}
void main()
{
Num a(10, 1);
Num b(10, 10);
Num c(0, 0);
c = Expression(a+b);
c.print();
}