Home > Back-end >  How can I invoke an overloaded () operator on the keyword this?
How can I invoke an overloaded () operator on the keyword this?

Time:11-04

The following works but feels ugly when I do the (*this)(5) part.

struct MyStruct
{
    void operator()(int a)
    {
        // Do something with "a"
    }

    void myFunc()
    {
        (*this)(5);
    }
};

I will need to overload the () operator and use it from within other class methods.

CodePudding user response:

You have a few options:

  • (*this)(5)

  • this->operator()(5)

  • or just operator()(5)

  • Create a method that you call from within the operator(), e.g.:

    void do_work(int a) { /* ... */ }
    void operator()(int a) { do_work(a); }
    void myFunc() { do_work(); }
    

Whichever you choose is just a matter of personal taste.

  • Related