假设我们有这样的东西:某个类 Foo ( 'FooInterface' ) 的接口(interface)和一个包含来自 'FooInterface' 的派生类的容器类 Bar。
现在,我将派生类( 'FooOne'、 'FooTwo' )类型的类型列表转发到容器类,并将它们的实例存储在一个小型的 'boost::hana::tuple' 后面。类型计算('FooTuple')。
现在如何根据“FooList”的大小使用取消引用的 this 指针初始化元组元素?
#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>)) {}
};
现在,您必须小心,因为这将复制每个 *this
在replicate
中创建元组时。如果您想要引用,请使用 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/