编译期编程的世界(3/3)

本文介绍GenScatterHierarchy和GenLinearHierarchy两种模板元编程技术。前者用于生成散乱的继承体系,后者则生成线性继承体系。文章深入探讨了这两种技术的具体实现及应用场景,并对比了它们在内存使用上的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.GenScatterHierarchy依据typelist生成散乱的继承体系

template    <class    TList,template <class> class Unit>
class    GenScatterHierarchy;

template    
<class T1,class T2,template <class> class Unit>
class GenScatterHierarchy<LOIK_TYPE_LIST2(T1,T2),Unit>
    :
public    GenScatterHierarchy<T1,Unit>
    ,
public    GenScatterHierarchy<T2,Unit>
{
}
;

template    
<class AtomicType,template <class> class Unit>
class    GenScatterHierarchy    :public    Unit<AtomicType>
{
}
;

template    
<template    <class>    class Uint>
class    GenScatterHierarchy<NullType,Unit>
{
}
;

让我们首先做点基础的工作,已经知道,子类指针可以向基类转换,这在多重继承的时候一样是可以的。这样对于一个GenScatterHierarchy对象来说,它可以准确任意转化成任何一个基类,唯一的问题是,typelist中某一类型不唯一怎么办?

让我们明白两点,GenScatterHierarchy是类基本的工具,所以对于typelist中类型重复我问题,它也只是生成了同样的一个类,但你必须承认通过不同的路径对同一个类继承了两次。如果你一定要对特定产出路径分选,那你要明白这不同路径的两个类是同一个类,如果你生成了对象,那有两份一样的对象。

获取特定路径产出的对象通用需要编译期推导,很幸运,我们可以,但是你不知道多少次重用了GenScatterHierarchy这个工具(这个类),因为你要找到特定的位置,而这个位置只可通过递归过程中的计数。

template    <class TList,template <class> class Unit>
Unit
<TList::Head>&    FieldHelper(GenScatterHierarchy<TList,Unit>& obj,Int2Type<0>)
{
    GenScatterHierarchy
<TList::Head,Unit>&    leftBase    = obj;
    
return    leftBase;
}


template    
<int i,class TList,template <class> class Unit>
Unit
<TypeAt<TList,i>::Result>&    FieldHelper(GenScatterHierarchy<TList,Unit>& obj,Int2Type<i>)
{
    GenScatterHierarchy
<TList::Tail,Unit>&    rightBase    = obj;
    
return    FieldHelper(rightBase,Int2Type<- 1>());
}


template    
<int i,class TList,template <class> class Unit>
Unit
<TypeAt<TList,i>::Result&    Field(GenScatterHierarchy<TList,Unit>& obj)
{
    
return    FieldHelper(obj,Int2Type<i>());
}

一如你已经见过的手法,但是你可能不明白为什么要如此费力构造这样一个东西,它有什么用呢?er,简单的说,它太有用了,它可以用来定义一个坐标,根据typelist的情况确定是多少维的,你可能对2维和3维比较熟悉。

2.GenLinearHierarchy生成线性继承体系

template    <class TList,template <class AtomicType,class Base> class Unit,class Root = EmptyType>
class GenLinearHierarchy;

template    
<class T1,class T2,template <class,class> class Unit,class Root>
class GenLinearHierarchy<Typelist<T1,T2>,Unit,Root>
    :
public    Unit<T1,GenLinearHierarchy<T2,Unit,Root>
{};

template    
<class T,template <class,class> class Unit,class Root>
class GenLinearHierarchy<LOKI_TYPELIST_1(T),Unit,Root>
    :
public    Unit<T,Root>
{};

其实,我倒觉得这里更直接,因为我们已经非常习惯编译递推的手法了。

GenLinearHierarchy和GenScatterHierarchy的比较:
GenScatterHierarchy使用了多重继承,你可能有多个指向虚函数表的指针,如果你比较关心大小,那使用GenLinearHierarchy是个不错的主意,你消除了多余的虚函数表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值