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?
compute(bla)
and call it insideoperator()
? Then you can callcompute
inside the class and use theoperator()
outside. – Vitor Pyoperator()
. – Oliver Charlesworthoperator()
. Operator() is a method with no name: It is the emperor's new method (as in the emperor's new clothes).operator()
looks just as ugly and just as naked from the outside as it does from the inside. What is wrong with a fully clothed function here, such asillumination
? – David Hammenoperator()
doesn't look at all ugly if you want to create an object that acts like a function. I agree that it makes very little sense if it's only for "internal" use, though. – Oliver Charlesworth