我是 C++ TMP 的新手。我将新创建的类型一一添加到全局 boost.hana::tuple 对象中。像这样的东西:
auto animals = boost::hana::make_tuple();
struct Fish { std::string name; };
using animals = boost::hana::append(animals, Fish);
struct Cat { std::string name; };
using animals = boost::hana::append(animals, Cat);
static_assert(animals == boost::hana::make_tuple(Fish, Cat), "");
基本上,我最终想要的是具有多种动物类型的
animals
。不过,我事先并不知道有多少种。随着越来越多的代码(头文件)被添加,animals
的列表也在增长。我希望每个头文件应该将自己的动物类型添加到animals
中。不同的头文件不知道其他头文件在做什么。不过,他们都知道全球 animals
列表。
我怎样才能实现这个目标?
可以实现自定义类型特征
list_append
,其 types
定义相同的模板类 T
,专门用于其所有模板参数和新类型 U
。
示例:
namespace detail {
template <typename, typename>
struct list_append
{};
template <template <typename...> typename T, typename... Vs, typename U>
struct list_append<T<Vs...>, U>
{ using type = T<Vs..., U>; };
}
template <typename T, typename U>
struct list_append
: detail::list_append<T, U>
{};
template <typename T, typename U>
using list_append_t = typename list_append<T, U>::type;