c++ - How to make types for indexing -
i have like:
array definition:
array<array<value, n_foo_per_bar>, n_bar> arr;
access function:
value getfoo(int baridx, int fooidx){ return arr[baridx][fooidx]; }
for-loop:
for(int = 0; < n_bar; ++){ for(int j = 0; j < n_foo_per_bar; j ++){ arr[i][j].dosomething(); } }
problem: indices foo , bar can mixed when using getfoo(...)
.
i define type baridx
, fooidx
, compiler should complain when mix them up.
the access function like:
function getfoo(badidx baridx, fooidx fooidx){ return arr[baridx][fooidx]; }
the for-loop like:
for(baridx = 0; < n_bar; ++){ for(fooidx j = 0; j < n_foo_per_bar; j ++){ arr[i][j].dosomething(); } }
so i'm looking how define type (a) issue warning/error when used @ wrong place (b) still behaves as integer possible, for loop , array access []. should work on cuda, prefer use simple language constructs rather perfect solution.
the difficulty doing can't inherit int in c++, need provide wrapper not implicitly converts , int
, provides necessary operators can things like:
baridx = 0; ++a;
you might want start simple 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 operators need later. define index classes this:
class baridx : public integralwrapper<int> {}; class fooidx : public integralwrapper<int> {};
alternatively, here seemingly pretty complete integral wrapper solution taken this question use.
Comments
Post a Comment