c++ - function pointer with known arguments -


i have lot of legacy code uses function pointer argument of form double (*f)(double). have requirement need call function class function definition uses member variables. do solve issue? example,

void legacy_function(double (*f)(double)) { .... }  class myclass {    double a;    double b;    double c;     void mymethod(...) {        // need call legacy_function() such uses , b 1 unknown        // a+b*x     }     

note cannot change definitions or declarations in legacy code.

i hope making sense. suggestions..

there's no clean way solve problem. has no elegant solution within bounds of standard language.

one thing can provide global or static variable serve this pointer intermediate callback wrapper function (see below), , write static intermediate callback wrapper function delecate call non-static class method

class myclass {   ...   static myclass *myclass_this;    double callback_wrapper(double d) {     assert(myclass_this != null);     return myclass_this->callback(d); // calls actual implementation   } }; 

also write actual callback implementation in myclass

class myclass {   ...   double callback(double d) {     // whatever want `a`, `b` etc.     return /* whatever */;   }   ... }; 

now can initialize myclass_this , use intermediate callback wrapper inside mymethod

... void mymethod(...) {   myclass_this = this; // initilize context   legacy_function(&callback_wrapper); } ... 

all this, of course, terribly inelegant since relies on global or static variables , therefore non-reentrant.

there alternative methods, happen non-portable , non-standard. (read closures , delegates).


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -