operator overloading – How can I “override” [] to accept two arguments in C++? – Education Career Blog

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_vectorbit_position

and sub-vectors are referenced like this:

my_vectormsb:lsb

or

my_vectormsb,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:

  1. using a range method:

    my_vector.range(msb,lsb)

  2. 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:

Apart from operator() all operators have a fixed arity, which effectively precludes any kind of change

You then have several solutions:

  • overload operator() instead: vector(msb, lsb)
  • use two successive invocations: vectormsblsb
  • overload the comma operator: vectormsb,lsb

The last solution matches the syntax you require, but is somewhat subtle:

  • you first need either msb or lsb to be of a custom type (for operators cannot be overloaded on built-ins only)
  • you then provide an overload of operator, for this type, returning a Range object
  • you finally provide a custom operator(Range) on your class

The 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_vectorfoo;

or in the new standard, I believe you can simply do:

my_vectorpos{1,2}

,

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.

,

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

Leave a Comment