Operator[][] overload

前端 未结 18 2048
轮回少年
轮回少年 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:39

    template
    struct indexer_t{
      F f;
      template
      std::result_of_t operator[](I&&i)const{
        return f(std::forward(i))1;
      }
    };
    template
    indexer_t> as_indexer(F&& f){return {std::forward(f)};}
    

    This lets you take a lambda, and produce an indexer (with [] support).

    Suppose you have an operator() that supports passing both coordinates at onxe as two arguments. Now writing [][] support is just:

    auto operator[](size_t i){
      return as_indexer(
        [i,this](size_t j)->decltype(auto)
        {return (*this)(i,j);}
      );
    }
    
    auto operator[](size_t i)const{
      return as_indexer(
        [i,this](size_t j)->decltype(auto)
        {return (*this)(i,j);}
      );
    }
    

    And done. No custom class required.

提交回复
热议问题