uchar
uchar

Reputation: 2590

Is there any way to call class operators with out using * , in a pointer to class type?

Is it possible to call operator[] with out using * when I have a pointer to the 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 :((
    }

Upvotes: 4

Views: 116

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275565

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

live example, but this is probably not what you want either.

In practice, just use the *. The * (as well as ->s) help remind you that the left hand side must be first checked for validity before it can be used in most contexts. After you check that your pointer is valid, you can dereference and store it in a reference for the duration of the current scope, and use [] to your heart's content.

The (*a) brackets get to be a bit annoying. On the other hand, possibly you should also avoid using pointers as much: modern C++ has moved away from using pointers, and would rather wrap things in smart pointers or pImpl wrappers and store the data in value-semantic types.

Then you only deal with pointers inside your smart pointer storage types, and when you want reseatable indirection to resources held elsewhere. Your nice and pretty pImpl wrappers are used more often, and they act like values even if most of their state is held dynamically.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

Yes, you should be able to use the -> operator, like this:

a->operator[] (2);

Demo on ideone.

If all you need is eliminating the asterisk, this should do the trick. If you are aiming for a better readability, this isn't of much help - you need to either avoid the pointer, or to 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 ideone).

Upvotes: 6

Related Questions