Kphysics
Kphysics

Reputation: 453

How do I call operator() on "this"?

I have a member function which needs to call operator() on the class instance (this), and I could not guess at the right syntax. I tried

  this();
  *this();
  this->();
  this->operator();

and a few other things, but the error messages are not very informative, so I dont know what am I doing wrong.

The closest I found on SE: How do I call a templatized operator()()?

Upvotes: 9

Views: 3445

Answers (3)

Kphysics
Kphysics

Reputation: 453

Use

 this->operator()();

Explanation:

  • this is a pointer,
  • -> is the right way to access a member function on a pointer to a class,
  • operator() is the name of the function,
  • the second () is the empty argument list of the function. Thus, the first pair of brackets is part of the functions's name and the second pair is to provide the argument(s), which might not be empty in general.

Upvotes: 16

Jose Maria
Jose Maria

Reputation: 465

I propose an example (test method):

#include <iostream>

class A
{
public:
    int operator()(int index)
    {
        return index + 1;
    }
    int test()
    {
        // call to operator ()
        return this->operator()(5);
    }
};

int main()
{
    A obj;
    std::cout << obj.test() << std::endl;
    std::cout << obj(7) << std::endl;
    std::cout << obj.operator()(9) << std::endl;
}

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234635

(*this)(/*parameters*/)

is probably the clearest way.

Upvotes: 21

Related Questions