用一个参数初始化boost :: hana :: tuple

时间:2017-02-15 11:41:33

标签: c++ boost template-meta-programming generic-programming boost-hana

假设我们有这样的东西:某个类Foo('FooInterface')的接口和包含'FooInterface'派生类的容器类Bar。

现在我将派生类('FooOne','FooTwo')类型的类型列表转发到容器类,并将它们的实例存储在一个小的'boost :: hana :: tuple'之后类型计算('FooTuple')。

现在如何使用解除引用的this-pointer初始化元组元素,具体取决于'FooList'的大小?

MCVE (Wandbox)

#include <iostream>

#include <boost/hana.hpp>

namespace hana = boost::hana;

template <typename FooList>
class Bar;

template <typename FooList>
class FooInterface
{
public:
    FooInterface(Bar<FooList>& bar) {}

public:
    virtual void foo() = 0;
};

class FooOne;
class FooTwo;

using MyFooList = decltype(hana::tuple_t<FooOne, FooTwo>);

class FooOne final
    : public FooInterface<MyFooList>
{
public:
    FooOne(Bar<MyFooList>& bar) 
        : FooInterface(bar)
    {}

public:
    void foo() override
    {
        std::cout << "FooOne!\n";
    }
};

class FooTwo final
    : public FooInterface<MyFooList>
{
public:
    FooTwo(Bar<MyFooList>& bar) 
        : FooInterface(bar)
    {}

public:
    void foo() override
    {
        std::cout << "FooTwo!\n";
    }
};

template <typename FooList>
class Bar
{
public:
    using FooTuple = typename decltype(hana::unpack(FooList(), hana::template_<hana::tuple>))::type;

    FooTuple foos{ *this, *this };
};

int main() 
{
   Bar<MyFooList> b;
   b.foos[hana::int_c<0>].foo();
   b.foos[hana::int_c<1>].foo();
}

输出:

FooOne!
FooTwo!

2 个答案:

答案 0 :(得分:2)

hana::replicate是你的朋友。

template <typename FooList>
class Bar {
    ...

    using FooTuple = ...;
    FooTuple foos;

    Bar() : foos(hana::replicate<hana::tuple_tag>(*this, hana::size_c<N>)) {}
};

现在,您必须小心,因为在*this中创建元组时,会复制每个replicate。如果您想要引用,请使用reference_wrapper,如下所示:

foos(hana::replicate<hana::tuple_tag>(std::ref(*this), hana::size_c<N>))

然后确保FooTuple中每个事物的构造函数都可以从reference_wrapper构造(如果他们接受引用就是这种情况)。

答案 1 :(得分:1)

不确定这是否是最简单的方法 - 但您可以尝试std::index_sequence来执行此操作:

template <typename FooList>
class Bar
{
    static constexpr size_t fooListSize = decltype(hana::size(std::declval<FooList>()))::value;
    template <std::size_t ...I>
    Bar(std::index_sequence<I...>) : foos{(I, *this)...} {}

public:
    using FooTuple = typename decltype(hana::unpack(FooList(), hana::template_<hana::tuple>))::type;

    Bar() : Bar(std::make_index_sequence<fooListSize>{}) {}

    FooTuple foos;
};
相关问题