基於原則設計是一種基於C++電腦程式設計規範,以原則(Policy)為基礎,並結合C++的模板元編程(template metaprogramming)。policy-based首見於 Andrei Alexandrescu 出版的 《Modern C++ Design》 一書以及他在C/C++ Users Journal雜誌專欄 Generic<Programming> 。
基本介紹
- 中文名:基於原則設計
- 外文名:Policy-Based Class Design
- 又稱:policy-based programming
簡介
template < class Policy1, class Policy2, class Policy3 > class PolicyBasedClass:public Policy1, public Policy2 { public: PolicyBasedClass(){}; };
Template Template Parameter
template < class T, template< class > class ReadPolicy, template< class > class WritePolicy > class ResourceManager : public ReadingPolicy< T >, public WritingPolicy< T > { public: void Read(); void Write(XmlElement*); void Write(DataSource*); };
void main() { ResourceManager< AnimationEntity, BinaryReader, BinaryWriter > ResMgr1; ResourceManager< ScriptEntity, TextReader, TextWriter > ResMgr2; }
示例
template< typename output_policy, typename language_policy>class HelloWorld : public output_policy, public language_policy{ using output_policy::Print; using language_policy::Message;public: //behaviour method void Run() { //two policy methods Print( Message() ); }};#include <iostream>class HelloWorld_OutputPolicy_WriteToCout{protected: template< typename message_type > void Print( message_type message ) { std::cout << message << std::endl; }};#include <string>class HelloWorld_LanguagePolicy_English{protected: std::string Message() { return "Hello, World!"; }};class HelloWorld_LanguagePolicy_German{protected: std::string Message() { return "Hallo Welt!"; }};int main(){/* example 1 */ typedef HelloWorld< HelloWorld_OutputPolicy_WriteToCout, HelloWorld_LanguagePolicy_English > my_hello_world_type; my_hello_world_type hello_world; hello_world.Run(); //returns Hello World!/* example 2 * does the same but uses another policy, the language has changed */ typedef HelloWorld< HelloWorld_OutputPolicy_WriteToCout, HelloWorld_LanguagePolicy_German > my_other_hello_world_type; my_other_hello_world_type hello_world2; hello_world2.Run(); //returns Hallo Welt!}