c++ - Boost Hana 编译时列表转换

标签 c++ boost metaprogramming boost-hana

我试图弄清楚如何使用 boost:hana 在编译时转换整数常量列表。

我的 list 是:

constexpr auto vals = hana::to<hana::tuple_tag>(hana::range_c<int, 0, 3>);

我要应用该功能:

constexpr auto Pow2(int i) { return 1 << i; }

但是

constexpr auto res = hana::transform(list, Pow2);

生成 hana::tuple<int, int, int> 的 res 类型。我不知道如何将 lambda 的参数移动到 hana::int_c 的模板参数中

// Compiler error: Non-type template argument is not a constant expression
constexpr auto Pow2(int i)
{
    return hana::int_c<1 << i>{};
}

最佳答案

在...

constexpr auto Pow2(int i) { return 1 << i; } 

... i是一个运行时整数。它不是一个“编译时友好”参数,因为它的值不存储为其类型的一部分。您应该传入 int_相反:

template <int X>
constexpr auto Pow2(hana::int_<X>) { return hana::int_c<1 << X>; }

用法:

constexpr auto vals = hana::to<hana::tuple_tag>(hana::range_c<int, 0, 3>);
constexpr auto res = hana::transform(vals, [](auto x){ return Pow2(x); });

static_assert(std::is_same_v<
    std::decay_t<decltype(res)>,
    hana::tuple<hana::int_<1>, hana::int_<2>, hana::int_<4>>
>);

wandbox example


显然,您也可以使用 lambda 来完成此操作。此外,boost::hana::int_有一个 operator<<返回 int_ 的重载:

hana::transform(vals, [](auto x){ return hana::int_c<1> << x; });

wandbox example

关于c++ - Boost Hana 编译时列表转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420303/

相关文章:

c++ - 如何在模板元编程中进行小于比较?

c++ - 为什么 RegisterClass 因 ERROR_NOT_ENOUGH_MEMORY 而失败?

c++ - CPlusPlus 模式 : create matching parenthesis or curly brace

c++ - 使用 HSV 范围逐像素过滤红色轮廓

C++ 是否可以加密通过命名管道发送的数据?

c++ - 如何在 boost 累加器中使用/访问用户参数?

c++ - 测试新运算符(operator)失败

groovy - 使用 Groovy 元编程替换 toString

C++ - 无法使用 msys2 和 cmake 链接到 Boost::logger

perl - 在 Perl5 中实现功能切换