How to declare a boolean Operator()?

Asked

Viewed 64 times

2

I understand what it does and its usefulness, however, during the researches I did found contradictory information regarding the syntax of a boolean operator.

I found 2 syntaxes:

bool operator() (Tipo variavel) const {}

and

operator() bool (Tipo variavel) const {}

Is there a difference between the two syntaxes? Or what changes is the writing preference?

What is that const indicates?

  • You can show the reference of where you saw both?

  • operator() bool const vi aqui -> https://stackoverflow.com/questions/5829487/how-do-i-override-the-bool-operator-in-a-c-class

  • bool operator() const is part of the project code I am part of: class CompareEggX { 
public:
 bool operator() ( APoint A1, APoint A2 ) const { 
 return (A1.m_x > A2.m_x); 
 } 
};

1 answer

1


Function call overload

The first is the operator overload function call, then the object of that type is called as a function according to the signing specified, in case the return would be a bool and would receive an argument of the kind Tipo, that operator shall be invoked.

Can be seen in documentation in the "Function call Operator".

In your example you have an object that is made to be compared, so a flame to the object will generate a boolean. Just because it is a comparison that should return this type, it is circumstantial. You will have to call as a function.

Overload of cast

The second is a form of cast which is also an operator, so it is taking a way to implicitly convert a data to a boolean value, so whenever an expression waits for a boolean and uses the object of this type where it has that operator it will execute that code and deliver the expected result.

But the syntax in the question is wrong.

Can be seen documentation.

I can’t say, but maybe your code should use this technique, so you don’t need to call it a function and it will have the intended value whenever the object is used in a context that requires a boolean. But it takes care to decide why, there are cases that can be make confusing and there is conversion unintentionally. There are those who think that no implicit conversion should occur to give more robustness to the code, but most prefer the ease.

Completion

So it’s two completely different operators.

The other question has already been answered in Statement const at the end of function in C++ and const before argument in method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.