I am trying to create a bit-vector class in C++ to model some hardware. In most HDLs (hardware description langauges) that I know, specific bits are referenced like this:
my_vector[bit_position]
and sub-vectors are referenced like this:
my_vector[msb:lsb]
or
my_vector[msb,lsb]
I want to be able to do something similar with my bit-vector class. Is there any way to tell operator[] to accept two arguments?
The alternatives I’ve considered are:
-
using a
rangemethod:my_vector.range(msb,lsb) -
using a string and parsing it:
my_vector["msb:lsb"]
But neither of them is attractive. The first, because it is too different from the way it’s modeled in HDL, the second because I don’t like dealing with strings when I don’t have to, and it seems inelegant.
What’s the best way to do this?
The issue:
You then have several solutions:
operator()instead:vector(msb, lsb)vector[msb][lsb]vector[msb,lsb]The last solution matches the syntax you require, but is somewhat subtle:
msborlsbto be of a custom type (for operators cannot be overloaded on built-ins only)operator,for this type, returning aRangeobjectoperator[](Range)on your classThe real bummer is the first point: that one of
msborlsbneed be of a custom type. This can be somewhat alleviated usingBoost.StrongTypedefwhich creates a custom type that mimicks an existing one.