1

我正试图围绕着伟大的 boost::hana 并试图弄清楚如何翻译一些老式的元组代码。

也许它有点特别,但我的类型既不可复制也不可移动,并且想将它们打包在容器中。考虑政策设计...

我想我只是不知道如何在价值世界中创建一个 hana 元组。我尝试的方式不起作用,因为make<Tuple>(CompT{}...)需要可复制或至少可移动的类型。

所以很可能这不是这样做的方法。还是这是hana的限制?

谢谢!

struct NonMoveable
{
    NonMoveable() = default;
    NonMoveable(const NonMoveable& other) = delete;

    int val;
};

struct Simple { int val; };

template <typename ...CompT>
struct OldSchoolContainer
{
    template <int I>
    auto& getComponent()
    {
        return std::get<I>(components);
    }

    std::tuple<CompT...> components;
};

template <typename ...CompT>
struct HanaContainer
{
    using Args_t = decltype(make<Tuple>(CompT{}...));

    template <int I>
    auto& getComponent()
    {
        return components[int_<I>];
    }

    Args_t components;
};

int main()
{
    OldSchoolContainer<Simple> simpleOsc;
    static_assert(std::is_same<Simple&, decltype(simpleOsc.getComponent<0>())>::value, "");

    HanaContainer<Simple> simpleHanaC;
    static_assert(std::is_same<Simple&, decltype(simpleHanaC.getComponent<0>())>::value, "");


    OldSchoolContainer<NonMoveable> nonmoveableOsc;
    static_assert(std::is_same<NonMoveable&, decltype(nonmoveableOsc.getComponent<0>())>::value, "");

    // !!! this does not compile because hana's tuple closure needs to either move or copy
    HanaContainer<NonMoveable> nonmoveableHanaC;
    static_assert(std::is_same<NonMoveable&, decltype(nonmoveableHanaC.getComponent<0>())>::value, "");

    return 0;
}
4

1 回答 1

2

hana::_tuple<...>您几乎可以将类型用作std::tuple. 因此,以下工作:

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


struct NonMoveable
{
    NonMoveable() = default;
    NonMoveable(const NonMoveable& other) = delete;

    int val;
};

struct Simple { int val; };

template <typename ...CompT>
struct HanaContainer
{
    template <int I>
    auto& getComponent()
    {
        return components[hana::int_<I>];
    }

    hana::_tuple<CompT...> components;
};

int main()
{
    HanaContainer<Simple> simpleHanaC;
    static_assert(std::is_same<Simple&, decltype(simpleHanaC.getComponent<0>())>::value, "");

    HanaContainer<NonMoveable> nonmoveableHanaC;
    static_assert(std::is_same<NonMoveable&, decltype(nonmoveableHanaC.getComponent<0>())>::value, "");

    return 0;
}
于 2015-07-24T06:46:52.417 回答