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:
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.
a simple struct with two members as a parameter to operator[]...
struct pos
{
int lsb;
int msb;
};
pos foo={1,2};
my_vector[foo];
or in the new standard, I believe you can simply do:
my_vector[pos{1,2}]
Two argument operator[] is not possible in C++. The names of, precedence of, associativity of, and arity of operators is fixed by the language.1 Operator() however can take two arguments...
use a language with array slices instead? =P
Is there any way to tell
operator[]
to accept two arguments?
No.
There's two common alternatives. One is to overload operator()
instead. You then have to invoke it using the ()
syntax.
The other one is to have operator[]
return a proxy object for which operator[]
is overloaded, too. This can be invoked like multi-dimensional arrays in C, with several [][]
in series.
The usual solution is to override the () operator. This lets you do things like my_vector(1, 2).
Work arounds using the [] operator are possible, but as Matthieu M. points out, you need a custom type to be involved.