Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

c++ - TMP: how to write template code which converts any struct into a tuple?

Is it possible to use template meta-programming to convert any struct or class into a tuple?

For instance:

struct Foo
{
  char         c;
  int          i;
  std::string  s;
};

typedef std::tuple< char, int, std::string >  Foo_Tuple;

It would be nice to have some template code which will generate Foo_Tuple automagically for me.

ANSWER

This is overkill for such a simple case, but for more elaborate cases (eg ORM or any time you need to write a lot of boiler-plate code, and a mere template or macro is inadequate for the task), Boost Mirror looks like it may be extremely useful. I have dug into Boost Mirror a bit more: the basic reflection functionality (in Mirror and Puddle) are not hard to understand, are quite easy to set-up and seem to be quite extensive (can handle many constructs, including C++11 enum classes, etc...). I find this basic functionality to be more than adequate - I can just use the MACROS to the extent that I want to expose my classes to Reflection (so that I don't have to write boiler-plate code). The Factory generators also seem to be very powerful (with the same initial macros set up, you can swap in any factory generator you like to output JSON, SOCI, or to a stream etc...), but has a larger learning curve/setup, if you want to write your own factory generators. One last couple of notes: with some minor tweaks, I was able to get it to work with C++11 on gcc 4.7.2; also, the documentation has been well DOxygenated and there seem to be more than sufficient examples to get going quickly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think that there's a way to do this in C++.

I don't know a way to enumerate the fields/types in a struct - if you could do that, I would think that constructing such a tuple would be fairly straightforward.

I believe that Boost.Fusion has a macro that helps with this called FUSION_ADAPT_STRUCT, but that's all manual.

The technical term for this is "reflection", and you can find lots of information about it by searching for "C++ reflection".

Here's one such article: How can I add reflection to a C++ application?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...