是否可以使用模板元编程将任何结构或类转换为元组?
例如:
struct Foo
{
char c;
int i;
std::string s;
};
typedef std::tuple< char, int, std::string > Foo_Tuple;
Run Code Online (Sandbox Code Playgroud)
有一些模板代码会自动为我生成Foo_Tuple会很不错.
回答
这对于这样一个简单的案例来说太过分了,但是对于更复杂的案例(例如ORM或任何时候你需要编写大量的样板代码,而单纯的模板或宏不适合这项任务),Boost Mirror看起来像它可能非常有用.我更多地挖掘了Boost Mirror:基本的反射功能(在Mirror和Puddle中)不难理解,很容易设置并且看起来相当广泛(可以处理许多构造,包括C++ 11枚举类等...).我发现这个基本功能已经足够了 - 我可以使用MACROS到我希望将我的类暴露给Reflection的程度(这样我就不必编写样板代码).Factory生成器似乎也非常强大(使用相同的初始宏设置,您可以交换任何您想要输出JSON,SOCI或流等的工厂生成器...),但具有更大的学习曲线/设置,如果你想编写自己的工厂发电机.最后几个注释:通过一些小的调整,我能够在gcc 4.7.2上使用C++ 11; 此外,文档已经充分加氧,似乎有足够的例子可以快速进行.
如何在对数(至少以二为底)编译时间(严格来说,以对数实例化数量)中定义聚合的数量?
我目前能做的就是在线性时间内实现期望的目标:
#include <type_traits>
#include <utility>
struct filler { template< typename type > operator type (); };
template< typename A, typename index_sequence = std::index_sequence<>, typename = void >
struct aggregate_arity
: index_sequence
{
};
template< typename A, std::size_t ...indices >
struct aggregate_arity< A, std::index_sequence< indices... >, std::__void_t< decltype(A{(indices, std::declval< filler >())..., std::declval< filler >()}) > >
: aggregate_arity< A, std::index_sequence< indices..., sizeof...(indices) > >
{
};
struct A0 {};
struct A1 { double x; };
struct A2 { int i; …Run Code Online (Sandbox Code Playgroud)