Operator[][] overload

前端 未结 18 1864
轮回少年
轮回少年 2020-11-22 05:46

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

18条回答
  •  再見小時候
    2020-11-22 06:19

    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);
        }
    };
    

提交回复
热议问题