Is it possible to overload []
operator twice? To allow, something like this: function[3][3]
(like in a two dimensional array).
If it is pos
It is possible to overload multiple [] using a specialized template handler. Just to show how it works :
#include
#include
#include
#include
#include
using namespace std;
// the number '3' is the number of [] to overload (fixed at compile time)
struct TestClass : public SubscriptHandler {
// the arguments will be packed in reverse order into a std::array of size 3
// and the last [] will forward them to callSubscript()
int callSubscript(array& v) {
return accumulate(v.begin(),v.end(),0);
}
};
int main() {
TestClass a;
cout<
And now the definition of SubscriptHandler
to make the previous code work. It only shows how it can be done. This solution is optimal nor bug-free (not threadsafe for instance).
#include
#include
#include
#include
#include
using namespace std;
template class SubscriptHandler;
template class SubscriptHandler_ {
ClassType*obj;
array *arr;
typedef SubscriptHandler_ Subtype;
friend class SubscriptHandler_;
friend class SubscriptHandler;
public:
Subtype operator[](const ArgType& arg){
Subtype s;
s.obj = obj;
s.arr = arr;
arr->at(Recursion)=arg;
return s;
}
};
template class SubscriptHandler_ {
ClassType*obj;
array *arr;
friend class SubscriptHandler_;
friend class SubscriptHandler;
public:
RetType operator[](const ArgType& arg){
arr->at(0) = arg;
return obj->callSubscript(*arr);
}
};
template class SubscriptHandler{
array arr;
ClassType*ptr;
typedef SubscriptHandler_ Subtype;
protected:
SubscriptHandler() {
ptr=(ClassType*)this;
}
public:
Subtype operator[](const ArgType& arg){
Subtype s;
s.arr=&arr;
s.obj=ptr;
s.arr->at(N-1)=arg;
return s;
}
};
template struct SubscriptHandler{
RetType operator[](const ArgType&arg) {
array arr;
arr.at(0)=arg;
return ((ClassType*)this)->callSubscript(arr);
}
};