The other answer points out why your code doesn't work. Here is a really ugly solution that sort of does, 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;
}
The rules for using pointers as template arguments require that the pointer passed in as an argument be a pointer to a global variable. That global variable can, of course, be declared in an anonymous namespace.
It's ugly, and if you wanted to have several possible instances of myMap possible called back with at the same time you'd need as many global MyFTWFunction variables as possible simultaneous instances of myMap. Mostly this automates the creation of a thunk function that uses the content of a global variable to fill in the missing parameter.
Here is a version that is a LOT less flexible that does approximately the same thing for this narrow case that may make it more obvious what's going on here:
#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 auto-generates thunk functions that stuff in the contents of a global variable into a call to your callback function.