Implementing Matlab's colon : operator in C++ expression templates class -
i'm implementing c++ expression templates library. have set proper submatrixexpr
class collect elements within matrix, enabling syntax like
b = submatrix(a,1,3,2,10);
which equivalent matlab's
b = a(1:3,2:10);
of course, matlab's syntax more confortable mine. question is
is there possibility set matlab's colon :
operator in c++?
thank in advance.
short answer: no. colon not valid c++ operator, cannot overloaded. , if could, still not possible achiev need easily, because surely have precedence on comma operator, make expression in lines of a((1:3),(2:10))
, , allowed overload operators if 1 of operands user defined type (which not case here).
so other operator in place, not looks this.
what can do: overload operator()
matrix class, sensible arguments. enable write b = a(1,3,2,10);
, if define operator()(int,int, int, int);
my preferred solution operator()
taking either 2 initializer_list
s in c++11 or 2 std::array<int,2>
. former have check list contains 2 elements, latter need awkward double brace initialization - might disappear in c++14 or later (n3526, afaik it's not in cd c++14). third possibility of course named class call, presenting range:
class matrix { /* ... */ public: matrix operator()(std::initializer_list<int> range1, std::initializer_list<int> range2); //or: matrix operator()(std::array<int,2> range1, std::array<int,2> range2); //or: matrix operator()(range range1, range range2); }; int main() { matrix a; /* ... */ matrix b = a({1,3}, {2,10}); //beware of a({1,3,2,4,5}, {0}) ! //or: matrix b = a({{1,3}}, {{2,10}}); //uhgs... //or: matrix b = a(range(1,3), range(2,10)); //more verbose, more understandable }
Comments
Post a Comment