Search code examples
c++oopoverloading

How can I invoke an overloaded () operator on the keyword this?


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.


Solution

  • 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(5); }
      

    Whichever you choose is just a matter of personal taste.


    Just for fun, here are some more (ridiculous) options:

    • std::invoke (mentioned in comments):

      std::invoke(&MyStruct::operator(), this, 5);
      
    • mem_fn:

      auto call_op = std::mem_fn(&MyStruct::operator());
      call_op(this, 5);
      
    • lambda:

      auto call_op = [this] (int a) { operator()(a); };
      call_op(5);
      
    • bind_front

      auto call_op = std::bind_front(&MyStruct::operator(), this);
      call_op(5);