开发者

Simulating C# indexer in C++

开发者 https://www.devze.com 2023-01-25 11:55 出处:网络
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?

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


No, unfortunately the [] operator in C++ only takes one argument. The best you can do to approximate a multiple argument syntax is to overload the () operator. This approach is used by the matrix class in the Boost linear algebra library so you can lookup by (row, column).

An alternative approach is to have the [] operator return a proxy class which also has an overloaded [] operator, allowing for syntax like my_object[0][1]. This is similar to the syntax you would get with native C N-dimensional arrays.


You can use std::pair, std::tuple or boost::tuple as operator[]'s argument to achieve effectively the same thing.

0

精彩评论

暂无评论...
验证码 换一张
取 消