Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating C# indexer in C++

Tags:

c++

indexing

As you know in C# classes we can define an indexr with more than one argument. But in C++ operator [ ] can accept one argument. Is there a way to wrtie an indexer in C++ with more than one argument?

indexer in C# :

public AnyType this[arg1 , arg2 , .....]
{
    get { ... };
    set { ... };
}

[ ] operator in C++ :

AnyType & operator [] ( arg )
{
   // our code  
}
like image 331
Hesam Qodsi Avatar asked Feb 26 '23 20:02

Hesam Qodsi


1 Answers

You can return a temporary, which holds the first index and has a reference the data source.

private:
    class BoundArg {
    private:
        Data& data;
        size_t i; 
    public:
        BoundArg (etc.)

        value_type& operator [] ( size_t j ) {
           return data.get ( i, j );
        }
    };

public:
value_type& get ( size_t i, size_t j ) ...

BoundArg operator [] ( size_t i )
{
   return BoundArg ( *this, i );
}

Usually it's not worth the complexity, unless you've got a 2D array stored as a 1D array, in which case the temporary is just a pointer to somewhere into the array.

public:
value_type& get ( size_t i, size_t j ) { 
   return data_ [ i * rowWidth_ + j ];
}

value_type* operator [] ( size_t i )
{
   return data_ + i * rowWidth_;
}
like image 142
Pete Kirkham Avatar answered Mar 07 '23 16:03

Pete Kirkham