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
}
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_;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With