用于模板的HANA类型

hana types for template-of-templates

本文关键字:HANA 类型 用于      更新时间:2023-10-16

我正在尝试生成一种使用boost :: hana但遇到麻烦的类型。

我有以下类

template<template<typename> typename BarModel>
struct Foo {
    BarModel<double> bar;
}
template<typename T>
struct BarOne {
    T x;
}
template<typename T>
struct BarTwo {
    T y;
}

我现在想为每个BarX<T>类创建一个Foo<BarImpl>

auto bar_types = hana::tuple_t<hana::template_t<BarOne>, hana::template_t<BarTwo>>;
hana::for_each(bar_types, [](auto t) {
    auto footype = SOMETHING(t);
});

问题,我不确定应该如何做到这一点。我的第一个尝试是做

using BarT = typename decltype(t)::type;
auto bar_t = BarT(); // template_t, can create BarX<T> classes
auto foo_t = hana::template_<Foo>; // <-- FAIL
auto foo_bar_t = foo_t(bar_t);

但这会失败

error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class ...> class F> constexpr const boost::hana::template_t<F> boost::hana::template_<F>’
note:   expected a template of type ‘template<class ...> class F’, got ‘template<template<class> class BarModel> class Foo’

该注释表明hana::template_与模板的模板不合适。是这样吗?如果是这样,是否有其他解决方案?

boost.hana不直接支持它,但是在这种情况下实现它只是几行代码。

检查一下:

#include <boost/hana.hpp>
namespace hana = boost::hana;
template <template <template <typename...> class> class F>
struct template_template_t
{
  template <template <typename...> class G>
  constexpr auto operator()(hana::basic_type<hana::template_t<G>>) const
    -> hana::type<F<G>>
  { return {}; }
};
template <template <template <typename...> class> class F>
constexpr auto template_template = template_template_t<F>{};
/*****/
template <template <typename...> class BarModel>
struct Foo {
  BarModel<double> bar;
};
template <typename T>
struct BarOne {
  T x;
};
template <typename T>
struct BarTwo {
  T y;
};
int main() {
  constexpr auto bar_types = hana::tuple_t<hana::template_t<BarOne>, hana::template_t<BarTwo>>;
  BOOST_HANA_CONSTANT_ASSERT(hana::equal(
    hana::transform(bar_types, template_template<Foo>)
  , hana::tuple_t<Foo<BarOne>, Foo<BarTwo>>
  ));
}