【发布时间】:2017-02-15 11:41:33
【问题描述】:
假设我们有这样的东西:某个类 Foo ('FooInterface') 的接口和一个容器类 Bar,其中包含来自 'FooInterface' 的派生类。
现在我将派生类 ('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!
【问题讨论】:
标签: c++ boost template-meta-programming generic-programming boost-hana