Another answer indicates why your code is not working. Here is a really ugly solution, kind of, for certain limited situations.
typedef int (*ftwpt)(const char*, const struct stat*, int); typedef boost::function<int(const char*, const struct stat*, int)> MyFTWFunction; template <MyFTWFunction *callback> class callback_binder { public: static int callbackThunk(const char *s, const struct stat *st, int i) { return (*callback)(s, i); } }; extern void register_callback(callback_t f); int random_func(const char *s, const struct stat *st, int i) { if (s && *s) { return i; } else { return -1; } } MyFTWFunction myfunc; int main(int argc, const char *argv[]) { myfunc = random_func; register_callback(&callback_binder<&myfunc>::callbackThunk); return 0; }
Rules for using pointers as template arguments require that the pointer passed as an argument be a pointer to a global variable. Of course, this global variable can be declared in an anonymous namespace.
This is ugly, and if you wanted to have several possible instances of myMap that could be called back, at the same time you would need as many global MyFTWFunction variables at the same time as myMap instances. It basically automates the creation of a thunk function that uses the contents of a global variable to populate the missing parameter.
Here is a version that LOT is less flexible, which does roughly the same for this narrow case, which may make what happens here more obvious:
#include <map> #include <string> using ::std::map; using ::std::string; typedef map<string, double*> myMap; typedef int (*callback_t)(const char *, struct stat *st, int); int myFunction(const char*, struct stat *st, int, myMap*); template <myMap **map_ptr> class myMap_binder { public: static int call_my_function(const char *s, struct stat *st, int i) { return myFunction(s, st, i, *map_ptr); } }; extern void register_callback(callback_t f); myMap *mainmap; myMap *othermap; int main(int argc, const char *argv[]) { myMap m_map; myMap m_map2; mainmap = &m_map; othermap = &m_map2; register_callback(&myMap_binder<&mainmap>::call_my_function); register_callback(&myMap_binder<&othermap>::call_my_function); return 0; }
As you can see, myMap_binder is a template that automatically generates thunk functions that contain the contents of a global variable into a call to your callback function.