Is there a way to call class operators without using * in a pointer to a class type?

Is it possible to call the [] operator without using * if I have a pointer to a class?

   class MyClass
    {
    public:
        void operator[](int n)
        {
            cout<<"In []";
        }
    };
    int main()
    {
        MyClass *a=new MyClass;
        (*a)[2];//work
        a[2];//It just do some pointer arithmetic ...too bad :((
    }
+4
source share
2 answers

Yes, you should be able to use an operator ->, for example:

a->operator[] (2);

Demo on ideon.

If you only need to exclude the asterisk, this should do the trick. If you're aiming for better readability, that doesn't help much - you need to either avoid the pointer, or use a regular member function:

class MyClass
{
public:
    void operator[](int n)
    {
        cout<<"In []";
    }
    // Add a regular function for use with pointers
    // that forwards the call to the operator[]
    void at(int n) { (*this)[n]; }
};

Now you can write a->at(2);

( Demo on ideon ).

+6
source
template<typename LHS> struct at_lhs_t { LHS lhs; };
static struct at_t {} at;
template<typename LHS>
at_lhs_t<LHS> operator%( LHS&& lhs, at_t )
{ return {std::forward<LHS>(lhs)}; }
template<typename LHS, typename RHS>
auto operator%( at_lhs_t<LHS>&& lhs, RHS&& rhs )
->decltype( (std::forward<LHS>(lhs.lhs))->operator[](std::forward<RHS>(rhs)) )
 { return ( (std::forward<LHS>(lhs.lhs))->operator[](std::forward<RHS>(rhs)) ); }

class MyClass
{
public:
    void operator[](int n)
    {
        std::cout<<"In []";
    }
};
int main()
{
    MyClass *a=new MyClass;
    a %at% 2;
}

, , , , .

*. * ( -> s) , , . , , , [] .

(*a) . , , : ++ pImpl - .

, . pImpl , , .

+1

Source: https://habr.com/ru/post/1526235/


All Articles