How can I “override” [] to accept two arguments in C++?

后端 未结 6 1164
[愿得一人]
[愿得一人] 2020-12-30 09:48

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:

相关标签:
6条回答
  • 2020-12-30 10:16

    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: vector[msb][lsb]
    • overload the comma operator: vector[msb,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.

    0 讨论(0)
  • 2020-12-30 10:17

    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}]
    
    0 讨论(0)
  • 2020-12-30 10:21

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

    0 讨论(0)
  • 2020-12-30 10:24

    use a language with array slices instead? =P

    0 讨论(0)
  • 2020-12-30 10:27

    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.

    0 讨论(0)
  • 2020-12-30 10:29

    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.

    0 讨论(0)
提交回复
热议问题