TMP:如何编写将任何结构转换为元组的模板代码?
是否可以使用模板元编程将任何结构或类转换为元组?
Is it possible to use template meta-programming to convert any struct or class into a tuple?
例如:
struct Foo
{
char c;
int i;
std::string s;
};
typedef std::tuple< char, int, std::string > Foo_Tuple;
如果有一些模板代码会自动为我生成 Foo_Tuple,那就太好了.
It would be nice to have some template code which will generate Foo_Tuple automagically for me.
回答
这对于这样一个简单的案例来说是多余的,但对于更复杂的案例(例如 ORM 或任何需要编写大量样板代码,而仅仅模板或宏不足以完成任务),Boost Mirror 看起来它可能非常有用.我对 Boost Mirror 进行了深入研究:基本的反射功能(在 Mirror 和 Puddle 中)并不难理解,很容易设置并且似乎相当广泛(可以处理许多结构,包括 C++11枚举类等...).我发现这个基本功能已经绰绰有余――我可以使用 MACROS 来将我的类暴露给反射(这样我就不必编写样板代码).工厂生成器似乎也非常强大(使用相同的初始宏设置,您可以换入任何您喜欢输出 JSON、SOCI 或流等的工厂生成器...),但学习曲线更大/setup,如果你想编写自己的工厂生成器.最后一点:通过一些小的调整,我能够让它在 gcc 4.7.2 上与 C++11 一起工作;此外,文档已经很好地进行了 Doxygenated,并且似乎有足够多的示例可以快速上手.
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.
推荐答案
我认为 C++ 中没有办法做到这一点.
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.
我相信 Boost.Fusion 有一个宏可以帮助解决这个问题,称为 FUSION_ADAPT_STRUCT,但这都是手动的.
I believe that Boost.Fusion has a macro that helps with this called FUSION_ADAPT_STRUCT, but that's all manual.
这方面的技术术语是反射",您可以通过搜索C++ 反射"找到很多关于它的信息.
The technical term for this is "reflection", and you can find lots of information about it by searching for "C++ reflection".
这是一篇这样的文章:如何向 C++ 添加反射申请?
相关文章