operator() in C++
I have an object that has a mathematical function behind it. It seems like a perfect candidate for operator()
.
Specifically its a light that has a different value for each (phi,theta) position on the sphere.
Now the thing is, when inside the class, accessing the light function has this crunky syntax:
double operator() ( double phi, double theta ) { // compute light function return sin(2*t) * cos(p) ; // (really开发者_如何学Python this is implemented as a function pointer, // so the light function can be changed) } void functionThatUsesLightFunction() {double val = ( 2.0, 4.0 ) ; // seems bad// Whoops! Doesn't work. double val2 = (*this)( 2.0, 4.0 ) ; // ok double val3 = operator()( 2.0, 4.0 ) ; // no thank you }
But from outside the class, it gets this really nice syntax like
foreach( theta on 0..PI ) foreach( phi on 0..2*PI ) val += light( theta, phi ) ;
Do you think I'm misusing operator()
here?
i think you should define yet another function, say calculate
, in the private section of the class, and call this function from operator()
and other member functions. That way, you wouldn't be calling operator()
from member functions, but you can still call it from outside the class. Somthing like this:
class Light
{
private:
double calculateLight( double phi, double theta )
{
return sin(2*t) * cos(p) ;
}
public:
double operator() ( double phi, double theta )
{
return calculateLight(phi, theta);
}
//...
void functionThatUsesLightFunction()
{
double val3 = calculateLight( 2.0, 4.0 );
}
};
//Outside the class
Light light;
//...
val += light( theta, phi ) ;
There is also a good advantage in adding calculateLight
function, as you can choose a good name for this function, which increases readability. operator()
adds nothing to the readability.
I don't see why you would use operator()
here. You don't access any object fields in the body of operator()
and neither you change object state. I'd rather create a static method or just a regular function...
YourClass::operator()
as in a.operator() (arguments)
as opposed to a(arguments)
is pretty fine. It's just a matter of getting used to. Use it for a while, together with the C++ style casts, it will make you feel more pedantic and you won't be bothered by it afterwards.
精彩评论