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 range
method:
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?
There are two techniques that can be used to reduce a functions' arguments. One of them is to refactor the function, making it smaller, consequently, reducing the arguments' number. The Extract Method technique can be use to achieve this goal.
Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.
The C language provides a method to pass parameters to the main() function. This is typically accomplished by specifying arguments on the operating system command line (console). There are two parameters passed to main().
Yes, we can give arguments in the main() function. Command line arguments in C are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution. The argc and argv are the two arguments that can pass to main function.
The issue:
Apart from
operator()
all operators have a fixed arity, which effectively precludes any kind of change
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:
msb
or lsb
to be of a custom type (for operators cannot be overloaded on built-ins only)operator,
for this type, returning a Range
objectoperator[](Range)
on your classThe real bummer is the first point: that one of msb
or lsb
need be of a custom type. This can be somewhat alleviated using Boost.StrongTypedef
which creates a custom type that mimicks an existing one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With