Speed ​​up serialization of NVP macros and non-XML element characters

When using a macro BOOST_SERIALIZATION_NVPto create a name-value pair for XML serialization, the compiler gladly allows the compilation of the following code, even if the element name is not a valid XML element, and exceptions occur when you try to actually serialize the object into XML:

BOOST_SERIALIZATION_NVP(_member[index])

The obvious solution is to use:

boost::serialization::make_nvp("ValidMemberName", _member[index])

But can anyone suggest a way to change boost so that illegitimate element names cause a compilation error? (thus, not relying on unit testing to catch the aforementioned subtle bug)


Edit:

One idea is to somehow declare a dummy local variable with the name of the element passed to the macro, assuming that the set of valid identifiers in C ++ is a subset of the valid XML elements. Not everyone is sure that this can be done, though.

+5
source share
3 answers

Quoting XML syntax for names:

NameStartChar ::=   ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
NameChar      ::=   NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]

I see the following differences from C ++ names: Leading _ can be reserved in C ++, depending on what follows; the colon, periods, and minus signs are valid in XML names. Unicode characters can also cause some sorrow in C ++, but they are mostly implementation dependent.

[# x0300- # x036F] ( ), .

, , - . <:/" > , XML. . - , - . , foo[1], &foo, *foo, foo=0 foo,bar. : {using namespace name;}. foo::bar, OK - foo:: bar XML.

+2

, , , . ++ A-Z, a-z, 0-9 , XML ( , Unicode ).

​​, :

#define SAFE_BOOST_SERIALIZATION_NVP(name) \
    { int name = 0; } ; BOOST_SERIALZATION_NVP(name)

, . , -, . , error: invalid intializer:

#include "boost/serialization/nvp.hpp"
#define SAFE_BOOST_SERIALIZATION_NVP(name) \
    { int name = 0; } ; BOOST_SERIALIZATION_NVP(name)

int main(int argc, char *argv[])
{
    int foo[3] = { 10, 20, 30 };
    int bar = 10;
    SAFE_BOOST_SERIALIZATION_NVP(foo[0]);
    return 0;
}

foo[0] bar SAFE_BOOST_SERIALIZATION_NVP, .

+1

C++ 11 :

    #define SAFE_BOOST_SERIALIZATION_NVP(name) \
        ([](){struct name{};}(), BOOST_SERIALIZATION_NVP(name))

XML, C++ (, , XML).


: , , , (ar & NVP(a) & NVP(b);). - , .


: @Eric Melski ( --extra define - --some "" -) @MSalters (- using namespace names--).

struct:

#define SAFE_BOOST_SERIALIZATION_NVP(name) \
    BOOST_SERIALIZATION_NVP(name); {struct name{};}

:

#undef BOOST_SERIALIZATION_NVP
#define BOOST_SERIALIZATION_NVP(name)                              \
    boost::serialization::make_nvp(BOOST_PP_STRINGIZE(name), name); {struct name{};}

, .

+1

All Articles