在下面的代码中,C 的基类 B1 的模板参数 OFFSET 依赖于 B0,而 B2 依赖于 B1。
这是通过在每次创建 C 实例时手动编写代码来完成的(在 main 方法中)。有没有办法将此功能转移到 C 的定义中?
template<int OFFSET>
struct A {
enum O { offset = OFFSET };
enum S { size = 2 };
};
template<int OFFSET>
struct B {
enum O { offset = OFFSET };
enum S { size = 4 };
};
template < typename B0, typename B1, typename B2 >
struct C : public B0, B1, B2 {
};
int main(int argc, const char *argv[])
{
// instance of C
C< A<1>,
B< A<1>::offset * A<1>::size >,
A<
B< A<1>::offset * A<1>::size >::offset *
B< A<1>::offset * A<1>::size >::size
>
> c1;
// does the same thing
C< A<1>,
B< A<1>::size >,
A<
A<1>::size *
B< A<1>::size >::size
>
> c2;
return 0;
}
编辑:
为了回答评论,我认为需要采取以下步骤来解决这个问题:
编写一个可以改变偏移量的元函数:set_new_offset,它为 T 定义类型 T<2>
使用 boost::mpl::times 计算新的偏移量
添加更多模板魔术...