跳转到内容

更多 C++ 惯用法/层次结构生成

来自维基教科书,开放的世界,开放的书籍

层次结构生成

[编辑 | 编辑源代码]

生成由各种行为策略组成的具体类

当一个解决方案需要许多不同的实现,这些实现可以以多种方式组合,每个实现共享或不共享各种装饰,传统的解决方案是多重继承,这会导致各种问题。层次结构生成是一种模式,通过它,可以连续继承各种基类来避免多重继承。

解决方案和示例代码

[编辑 | 编辑源代码]
#include <iostream>

//prototype
template <template <class> class ... _PolicyTs> struct GenHierarchy;

//specialization for N policies constructs inheritance hierarchy
template <template <class> class _HeadPolicyT, template <class> class ... _TailPolicyTs>
struct GenHierarchy<_HeadPolicyT, _TailPolicyTs...> : _HeadPolicyT < GenHierarchy<_TailPolicyTs...> > {};

//inheritance hierarchy terminator and base class for concrete implementations
template <> struct GenHierarchy < > {};

//dance behavior policies
template <typename _ParentT> struct DanceA : _ParentT{
	void Dance(){ std::cout << __FUNCTION__ << std::endl; }
};

template <typename _ParentT> struct DanceB : _ParentT{
	void Dance(){ std::cout << __FUNCTION__ << std::endl; }
};

template <typename _ParentT> struct DanceC : _ParentT{
	void Dance(){ std::cout << __FUNCTION__ << std::endl; }
};

//joke behavior policies
template <typename _ParentT> struct JokeA : _ParentT{
	void Joke(){ std::cout << __FUNCTION__ << std::endl; }
};

template <typename _ParentT> struct JokeB : _ParentT{
	void Joke(){ std::cout << __FUNCTION__ << std::endl; }
};

template <typename _ParentT> struct JokeC : _ParentT{
	void Joke(){ std::cout << __FUNCTION__ << std::endl; }
};

//sing behavior policies
template <typename _ParentT> struct SongA : _ParentT{
	void Sing(){ std::cout << __FUNCTION__ << std::endl; }
};

template <typename _ParentT> struct SongB : _ParentT{
	void Sing(){ std::cout << __FUNCTION__ << std::endl; }
};

template <typename _ParentT> struct SongC : _ParentT{
	void Sing(){ std::cout << __FUNCTION__ << std::endl; }
};

//combine some behavior policies into concrete types
using BozoTheClown = GenHierarchy < DanceA, JokeB, SongC > ;
using HowdyDoody = GenHierarchy < DanceB, JokeA, SongA > ;
using RedButtons = GenHierarchy < DanceC, JokeC, SongB > ;

template <typename _Ty> void Entertain(_Ty oEntertainer){
	oEntertainer.Sing();
	oEntertainer.Dance();
	oEntertainer.Joke();
}

int main(){
	Entertain(BozoTheClown());
	Entertain(HowdyDoody());
	Entertain(RedButtons());
	return 0;
}

在上面的示例中,BozoTheClown 声明是以下内容的简写

struct BozoTheClown : DanceA<JokeB<SongC<GenHierarchy<>>>>{};

这与以下内容相同

struct GenHierarchy{};
struct SongC : GenHierarchy{ void Sing(){ std::cout << __FUNCTION__ << std::endl; } };
struct JokeB : SongC{ void Joke(){ std::cout << __FUNCTION__ << std::endl; } };
struct DanceA : JokeB{ void Dance(){ std::cout << __FUNCTION__ << std::endl; } };
struct BozoTheClown : DanceA{};

行为策略必须遵循此概念

template <typename _ParentT> struct Base : _ParentT
华夏公益教科书