1

I have to write a library exporting data to various formats. Every format is a type of a given boost::variant, e.g.

typdef boost::variant<csv, xml, hdf5> TFormat

with formats csv, xml and hdf5. This approach worked quite good for me. The library should be quite versatile and open for possible extensions from the client side. Hence, it would be nice if clients could add user-defined formats in a unified manner.

I would prefer that a I client can add several macros like

REGISTER_FORMAT(binary)
REGISTER_FORMAT(mpeg)

and afterwards my typedef magically changes to

typedef boost::variant<csv, xml, hdf, binary> TFormat.

I already figured out how to construct a type dynamic boost::variant using the following mpl-code that luckily compiles with MSVC2010.

#include <boost/variant/variant.hpp>
#include <boost/mpl/vector.hpp>

int main() {
    // Adding the type int, to a vector containing the types double and std::string
    using namespace boost;
    typedef mpl::vector< double, std::string > DefaultTypes;
    typedef mpl::push_front< DefaultTypes, int >::type ExtendedTypes;

    // typedef TFormat of type boost::variant<double, std::string, int>
    typedef boost::make_variant_over< ExtendedTypes >::type TFormat;
    return 0;
}

Still I'm not able to implemented the mentioned macro, since it is not clear beforehand how often a client would call REGISTER_FORMAT or if he would use the macro at all.

Does anyone has an idea how to implement such a macro or something similar?

Aleph0
  • 5,816
  • 4
  • 29
  • 80
  • 2
    I think this might actually be possible using the stateful template technique, but this is such a weird technique that I would recommend not using it. Also, it definitely won't work on VS2010. http://b.atch.se/posts/constexpr-meta-container/ – Sebastian Redl Feb 19 '16 at 10:00
  • Is it OK to recompile the library? How dynamic this should be? – Karoly Horvath Feb 19 '16 at 10:07
  • I have no problem in recompiling the library, as it would be used in-house only. – Aleph0 Feb 19 '16 at 10:09
  • Many thanks for the link. I really don't want to use weird techniques. :-) – Aleph0 Feb 19 '16 at 10:11

1 Answers1

1

I would prefer that a I client can add several macros like

It is impossible. C preprocessor has no "stack", no "variables", no "state". The only state you have is inside the expansion you are currently in. You can't "save stuff for later" or even assign anything. It is not possible for a previous macro to affect the next one.

or something similar?

You can use a different preprocessor, like M4, however if the macro calls span multiple files integrating it may be really hard.

And as mentioned, you could possibly use stateful templates tricks to accumulate the types.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111