c++ - 使用一个参数初始化 boost::hana::tuple

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

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

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

现在如何根据“FooList”的大小使用取消引用的 this 指针初始化元组元素?

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!

最佳答案

hana::replicate是你的 friend 。

template <typename FooList>
class Bar {
    ...

    using FooTuple = ...;
    FooTuple foos;

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

现在,您必须小心,因为这将复制每个 *thisreplicate中创建元组时。如果您想要引用,请使用 reference_wrapper像这样:

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

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

关于c++ - 使用一个参数初始化 boost::hana::tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42248393/

相关文章:

c++ - 如何执行高效的集合交集操作?

c++ - 来自 std::vector<double> 的未格式化流输入

c++ - Boost:单线程 IO 服务

c++ - 检测是否存在具有给定签名的函数

c++ - 使用指针复制和增长现有数组

c++ - 在迭代期间更改集合的最佳方法是什么?

c++ - SFINAE 和可变参数模板类

c++ - 标签调度相对于正常重载解析的优势

c++ - 标准函数和操作在类构造函数中不起作用

c++ - 如何检查 Boost::asio 中是否存在套接字连接?