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 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 fromoperator()and other member functions. That way, you wouldn’t be callingoperator()from member functions, but you can still call it from outside the class. Somthing like this:There is also a good advantage in adding
calculateLightfunction, as you can choose a good name for this function, which increases readability.operator()adds nothing to the readability.