c++ pointers to overloaded functions

耗尽温柔 提交于 2019-12-10 20:32:10

问题


I'm trying to expose a overloaded function using boost::python. the function prototypes are:

#define FMS_lvl2_DLL_API __declspec(dllexport)
void FMS_lvl2_DLL_API write(const char *key, const char* data);
void FMS_lvl2_DLL_API write(string& key, const char* data);
void FMS_lvl2_DLL_API write(int key, const char *data);

I'v seen this answer: How do I specify a pointer to an overloaded function?
doing this:

BOOST_PYTHON_MODULE(python_bridge)
{
    class_<FMS_logic::logical_file, boost::noncopyable>("logical_file")
        .def("write", static_cast<void (*)(const char *, const char *)>( &FMS_logic::logical_file::write))
    ;
}

results with the following error:

error C2440: 'static_cast' : cannot convert from 'overloaded-function' to 'void (__cdecl *)(const char *,const char *)'
      None of the functions with this name in scope match the target type

trying the following:

void (*f)(const char *, const char *) = &FMS_logic::logical_file::write;

results:

error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'void (__cdecl *)(const char *,const char *)'
          None of the functions with this name in scope match the target type

what's wrong and how to fix it?

EDIT I forgotten to mention a few things:

  • I'm using vs2010 pro on win-7
  • write is a member function of logical_file
  • FMS_logic is a namespace

回答1:


Well the second attemp should work, if write is a pure function. From your code it seems you do have a memberfunction. Pointers to member-functions are ugly, you'd rather use a function object. However: you would have to post the whole code, it is not clear whether write is a member-function or not.

Edit: if it is a member-function of FMS_logic::logical_file the syntax would be:

void (FMS_logic::logical_file::*f)(const char *, const char *) = &FMS_logic::logical_file::write;

This just applies for non-static member function, i.e. if a function is static or logical_file is just a namespace it is as you wrote it before.




回答2:


Your code doesn't work because your function pointer type is wrong. You need to include all type qualifiers (your DLL qualifier is missing) and, as Klemens said, the class name. Putting this together, your code should read

.def("write", static_cast<void FMS_lvl2_DLL_API
                            (FMS_logic::logical_file::*)(const char *, const char *)>
                         (&FMS_logic::logical_file::write))

Thanks for the hint with the static_cast<>, I had the same problem as you, just without the dllexport, and after adding the static_cast it works :-)



来源:https://stackoverflow.com/questions/17852738/c-pointers-to-overloaded-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!