我如何“覆盖” []接受C ++中的两个参数? [英] How can I "override" [] to accept two arguments in C++?

查看:79
本文介绍了我如何“覆盖” []接受C ++中的两个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C ++中创建一个位向量类来模拟一些硬件。在我知道的大多数HDL(硬件描述语言)中,具体的位被引用如下:

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]

和子向量的引用如下:

my_vector[msb:lsb]

my_vector[msb,lsb]


$ b b

我想能够做一些类似于我的位向量类。有没有办法告诉 operator [] 接受两个参数?


  1. 使用范围方法:

my_vector.range(msb,lsb)

并解析它:

my_vector [msb:lsb]

但他们都不具有吸引力。第一个,因为它与HDL中的建模方式太不同了,第二个因为我不喜欢处理字符串,当我不需要,它似乎不起眼。

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?

推荐答案

问题:


除了 operator()所有运算符都有一个固定的数,这有效地排除了任何变化

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

然后您有几个解决方案:

You then have several solutions:


  • overload operator()改为:向量(msb,lsb)

  • 使用两个连续的调用: vector [msb] [lsb]

  • 重载逗号运算符: vector [msb,lsb] code>

  • 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:


  • 您首先需要 msb lsb 自定义类型(仅适用于内置函数不能重载的操作)

  • 然后为此类型提供运算符的重载,返回 Range 对象

  • 最后提供一个自定义 operator [](Range)

  • 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

真正的问题是第一点: msb lsb 需要是自定义类型。这可以使用 Boost.StrongTypedef 稍微减轻,这会创建一个模仿现有类型的自定义类型。

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.

这篇关于我如何“覆盖” []接受C ++中的两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆