使用hana :: transform在C ++ 14中转换元组内部的类型

时间:2018-04-11 14:23:15

标签: c++ boost c++14 metaprogramming boost-hana

我正在尝试使用Boost的hana::transform更改hana::tuple内的类型。举个例子,说我有

constexpr auto some_tuple = hana::tuple_t<int, char *, bool>;

我想制作

constexpr auto transformed_tuple = hana::tuple_t<std::vector<int>,
                                                 std::vector<char *>, 
                                                 std::vector<bool>>;

尝试1

解决方案似乎很容易:使用hana::transform并使应用函数返回hana::type_c<std::vector<decltype(T)::type>>。但是,我无法做到这一点:

constexpr auto transformed_tuple = hana::transform(some_tuple, [](auto T) {
    using inner_type = typename decltype(T)::type;
    return hana::type_c<std::vector<inner_type>>;
});

这有一个问题,lambda表达式不是constexpr - 我想留在C ++ 14中,即lambdas不能是constexpr

尝试2

我的下一个想法:如果我将hana::transform包裹到decltype中,然后使用hana::type_c怎么办?这样,lambda永远不需要被评估(只需要推导它的返回类型),并且constexpr不应该重要:

constexpr auto transformed_tuple = 
    hana::type_c<decltype(hana::transform(some_tuple, [](auto T) {
        using inner_type = typename decltype(T)::type;
        return hana::type_c<std::vector<inner_type>>;
    }))>;

但是,现在我遇到的问题是lambda表达式可能不会出现在“未评估的上下文”中。

我的做法完全错了吗?我应该使用除hana::transform以外的其他东西吗?

感谢您的帮助。

修改

示例代码:

#include <boost/hana.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
namespace hana = boost::hana;

#include <vector>

constexpr auto some_tuple = hana::tuple_t<int, char *, bool>;

/** What I want:
 *
 *   constexpr auto transformed_tuple 
 *       = hana::tuple_t<std::vector<int>,
 *           std::vector<char *>, 
 *           std::vector<bool>>;
**/

#if ATTEMPT1
    constexpr auto transformed_tuple = hana::transform(some_tuple, [](auto T) {
        using inner_type = typename decltype(T)::type;
        return hana::type_c<std::vector<inner_type>>;
    });

#elif ATTEMPT2
    constexpr auto transformed_tuple = hana::type_c<decltype(hana::transform(some_tuple, [](auto T) {
        using inner_type = typename decltype(T)::type;
        return hana::type_c<std::vector<inner_type>>;
    }))>;

#endif

1 个答案:

答案 0 :(得分:6)

Boost.Hana有hana::template_用于将类型应用于返回类型的模板。

#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/transform.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
#include <vector>

namespace hana = boost::hana;


int main() {
    constexpr auto some_tuple = hana::tuple_t<int, char *, bool>;
    constexpr auto expected_tuple = hana::tuple_t<std::vector<int>,
                                                  std::vector<char*>,
                                                  std::vector<bool>>;

    constexpr auto transformed_tuple = hana::transform(some_tuple, hana::template_<std::vector>);

    BOOST_HANA_CONSTANT_CHECK(transformed_tuple == expected_tuple);
}