using opAssign or having my own assign function
Bill Baxter
dnewsgroup at billbaxter.com
Tue Sep 4 22:44:55 PDT 2007
Martin d Anjou wrote:
> Hi,
>
> I am trying to build a data type where a key characteristic is that the
> data holding capacity is fixed and never changing, and the declaration
> looks like this:
>
> auto a = BitVector(4); // "a" can hold unsigned numbers from 0 to 15
> auto b = BitVector(10); // 10 bits of data
> auto c = BitVector(79); // etc.
>
> Say I now want to add b and c, and store the result in a, while
> preserving the property that "a" has to have a capacity of 4 bits only.
> Adding and truncating the upper bits to fit in "a" is the easy part. The
> problematic part is stating that the result of the addition goes to
> variable "a".
>
> I was first tempted to simply say "a=b+c", but b+c will return a new
> instance of BitVector, scrap the original "a", and loose the holding
> capacity of "a". I thought of overloading opAssign(), but I can't do
> "BitVector opAssign(BitVector other) { ... }".
>
> So I came to the conclusion the least non-intuitive thing to do would be
> "a.assign(b+c)", which preserves the storage capacity declared for
> variable "a", and does not create a new instance for "a".
>
> Question: Is there a better way to do this?
>
> Question: Is there a chance opAssign could be used for this kind of
> thing at all in the future?
>
> Thanks,
> Martin
The only other thing that comes to mind is that you could use the
expression object trick as in Blitz++ et al. Have opAdd return a
BitVectorAddExpr, and then give BitVector an opAssign from
BitVectorAddExpr that will just trigger a call to a.assign(b+c).
struct BitVector
{
...
BitVectorAddExpr opAdd(ref BitVector b, ref BitVector c)
{ return BitVectorAddExpr(&b,&c); }
void opAssign( BitVectorAddExpr expr ) { a.assign(*expr.L+*expr.R); }
}
struct BitVectorAddExpr
{
static typeof(*this) opCall( . . . ) {. . . }
BitVector *L;
BitVector *R;
}
--bb
More information about the Digitalmars-d
mailing list