如何使索引的类型 [英] How to make types for indexing

查看:127
本文介绍了如何使索引的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的:

数组定义:

array<array<Value, N_FOO_PER_BAR>, N_BAR> arr;

存取功能:

Value getFoo(int barIdx, int fooIdx){
  return arr[barIdx][fooIdx];
}

For-loop:

for(int i = 0; i < N_BAR; i ++){
  for(int j = 0; j < N_FOO_PER_BAR; j ++){
    arr[i][j].doSomething();
  }
} 

问题:使用 getFoo(...)时,foo和bar很容易混淆。

Problem: Indices for foo and bar can easily get mixed up when using getFoo(...).

一个类型 BarIdx FooIdx ,然后编译器会在我混淆时提出抱怨。

I would like to define a type BarIdx and FooIdx and then the compiler should complain when I mix them up.

然后,访问函数将如下所示:

The access function would then look like:

function getFoo(BadIdx barIdx, FooIdx fooIdx){
  return arr[barIdx][fooIdx];
}

for-loop可能如下所示:

The for-loop could look like:

for(BarIdx i = 0; i < N_BAR; i ++){
  for(FooIdx j = 0; j < N_FOO_PER_BAR; j ++){
    arr[i][j].doSomething();
  }
} 

所以我在寻找如何定义一个类型(a)将在错误的位置使用时发出警告/错误,但是(b)仍然尽可能地表现为整数,对于使用[]的for循环和数组访问。这应该也适用于CUDA,所以我宁愿使用简单的语言结构,而不是一个完美的解决方案。

So I'm looking how to define a type which (a) will issue a warning/error when used at the wrong place but (b) still behaves as much as an integer as possible, for for loop and array access with []. This should also work on CUDA, so I would prefer to use simple language constructs rather than a perfect solution.

推荐答案

这样做是因为您不能简单地继承自int 在C ++中,所以你需要提供一个包装器,它不仅隐式地转换和从 int ,而且还提供了所有必要的操作符,以便你可以做像: p>

The difficulty with doing this is that you can't simply inherit from int in C++, so you need to provide a wrapper which not only implicitly converts to and from int, but also provides all the necessary operators so that you can do things like:

BarIdx a = 0;
++a;

您可能希望从这样简单的开始:

You might want to start with something simple like this:

template <typename T>
class IntegralWrapper {
    T value;
public:
    typedef T value_type;
    IntegralWrapper() :value() {}
    IntegralWrapper(T v) :value(v) {}
    operator T() const { return value; }
};

然后添加您以后需要的任何运算符。然后你可以这样定义你的索引类:

Then add any operators you need later. You would then define your index classes like this:

class BarIdx : public IntegralWrapper<int> {};
class FooIdx : public IntegralWrapper<int> {};

或者,这里是一个看起来相当完整的整体封装解决方案取自这个问题,你可能会使用。

Alternatively, here is a seemingly pretty complete integral wrapper solution taken from this question which you could probably use.

这篇关于如何使索引的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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