|
Boost Users : |
Subject: [Boost-users] [proto] baby steps learning with proto, proxy object
From: alfC (alfredo.correa_at_[hidden])
Date: 2010-10-07 17:52:48
Hi,
This can be an exercise for definining the scope of Boost.Proto for
little things. I have a histogram class that internally looks like
this
class histogram{
...
bool operator()(double const& x){return impl.increment(x);}
bool operator()(double const& x, double const& weight){return
impl.accumulate(x, weight);}
};
histogram h( .. bin spec .. );
double x = ... ;
so to add a count to the bin of x, I call
h(x);
to add a count with weigh w to bin x, I call
h(x,w);
so far so good. Now suppose I want to "improve" the syntax. The
desired syntax would be:
h[x]++;
h[x]+=w;
I don't want to expose the internal representation of the bins, so I
can't return a reference to something from h[x].
So I guess we can create a proxy of the expression h[x] , "subindex of
historgram with double". The proxy can be used with the syntax to call
either accumulate or increment depending on the application of += or +
+ to the proxy.
The naive implementation is this:
class histogram{
...
private:
struct proxy_histogram_subscript{
histogram& self;
double const& x;
proxy_histogram_subscript(histogram& self, double const& x) :
self(self), x(x){}
proxy_histogram_subscript const& operator++()
const{self.increment(x); return *this;}
bool operator++(int) const{return self.increment(x);}
bool operator+=(double const& weight) const{return
self.accumulate(x, weight);}
};
public:
proxy_histogram_subscript operator[](double const& x){
return proxy_histogram_subscript(*this, x);
}
};
which allows the desired syntax. The question is, can Boost.Proto do
better? What I don't understand is how proto can make such a mini
language *inside* the class. Hopefully without adding to much lines of
code.
I can see that one could create a histogram terminal, but that will be
public (e.g. from the main program) and that will allow to create all
sorts of expression involving brackets of anything.
Thank you,
Alfredo
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net