3

我正在尝试使用 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;
}

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

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_不适用于模板模板。是这样吗?如果是这样,是否有替代解决方案?

4

1 回答 1

1

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>>
  ));
}
于 2017-12-07T22:47:17.763 回答