Boost logo

Boost Users :

Subject: [Boost-users] [Bind] Representing a member function as C function pointer?
From: Roland Bock (rbock_at_[hidden])
Date: 2009-02-02 02:45:39


Hi,

maybe this is stupid, but I wonder if my code could become more elegant.
I am using expat for XML parsing, which is working fine, but could be nicer:

I have a class (XmlParser) which provides all the handlers for SAX
parsing required by expat, but I can't figure out how to use them directly?

When initializing expat, I give it a pointer to an XmlParser object and
then register handlers:

--------------------------
static void expatStartElementHandler (void* pUserData,
                                       const char* element,
                                       const char** attr)
{
    XmlParser* xmlParser = reinterpret_cast<XmlParser*>(pUserData);
    xmlParser->startElement (element, attr);
}

static void expatEndElementHandler (void* pUserData,
                                     const char* element)
{
    XmlParser* xmlParser = reinterpret_cast<XmlParser*>(pUserData);
    xmlParser->endElement (element);
}

void XmlParser::init()
{
    parser_ = XML_ParserCreate ("UTF-8");
    XML_SetUserData (parser_, this);
    XML_SetElementHandler (parser_,
      expatStartElementHandler,
      expatEndElementHandler);
    //...
}
-------------------------

I would prefer to get rid of those static non-member functions and their
reinterpret_cast and do something like

// does not work
XML_SetElementHandler (parser_,
    boost::bind(&XmlParser::startElement, this, _2, _3),
    boost::bind(&XmlParser::endElement, this, _2));

Is there a nice way to do this with bind?

Regards,

Roland


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net