我试图使用c ++模板元编程实现以下功能.我希望建立一个类型列表,然后一起收集这些类型,并在列表上进行进一步的编译时处理.例如:
foo.h中:
class Foo { ... };
// INSERT ANY CODE HERE
Run Code Online (Sandbox Code Playgroud)
bar.h:
class Bar { ... };
// INSERT ANY CODE HERE
Run Code Online (Sandbox Code Playgroud)
main.h:
#include "foo.h"
#include "bar.h"
struct list_of_types {
typedef /* INSERT ANY CODE HERE */ type;
};
Run Code Online (Sandbox Code Playgroud)
我可以在上面的插槽中插入任何代码,只要list_of_types :: type解析为包含类型Foo和Bar的列表的某些表示(例如boost :: mpl :: vector).以下限制适用:
foo.h中的代码不应该知道bar.h中的代码,反之亦然.应该可以在main.h中更改#include指令的顺序,而不是更改任何其他代码.
如果我包含更多类型添加到列表中的标题,则main.h中的代码不应该更改.
类型列表必须在编译时可用.我打算进一步进行涉及清单的元编程.
使用C++ 14和奇怪的重复模板模式(CRTP)和可能的Boost.Hana(或者boost::mpl
如果你愿意)的某种组合,我可以在编译时(或静态初始化时间)构建一个类型列表而不需要显式声明吗?
举个例子,我有类似的东西(见上Coliru):
#include <iostream>
#include <boost/hana/tuple.hpp>
#include <boost/hana/for_each.hpp>
namespace
{
struct D1 { static constexpr auto val = 10; };
struct D2 { static constexpr auto val = 20; };
struct D3 { static constexpr auto val = 30; };
}
int main()
{
// How to avoid explicitly defining this?
const auto list = boost::hana::tuple< D1, D2, D3 >{};
// Do something with list
boost::hana::for_each( list, []( auto t ) { std::cout …
Run Code Online (Sandbox Code Playgroud)