Magic C++ (函数指针)(xml配置控件样式)
来源:互联网 发布:高新区行知小学地址 编辑:程序博客网 时间:2024/04/30 16:02
C++ is so magic !!!
问题起源:
我在业余时间编写基于WTL的控件重绘,为了灵活设置控件的各种样式,我选择了使用xml来配置控件的样式(比如文字颜色,字体,背景颜色)。其中build.xml用来设置控件类型、位置、文字、样式,skin.xml来设置颜色、字体、图片。
首先定义一个类UIData,提供接口LoadCtrl(从build.xml读取位置信息)和LoadCss(从skin.xml读取样式)。
然后定义一个类ICtrl(继承UIData)作为控件基类,提供接口Create。
在IForm中提供一个接口Find
build.xml
<main type="Form" rect="0,0,500,400" css="public">
<label type="Label" rect="0,0,120,20" text="hello" css="public">
</main>
ICtrl* Find(const string name); 将name传入后在Find内部先找出该name对应的type,接着发现该type是Label于是new ILabel,之后再LoadCtrl(该函数最后会调用LoadCss的),最后返回这个ILabel(也可以在返回前调用Create)。
上面是铺垫,下面是问题:在Find中,传入一个name读取对应的type之后,如何只用一步就返回一个new ILabel?
常规做法:
ICtrl* c = nullptr;
if(type == "Label") c = new ILabel;
else if(type == "Button") c= new IButton();
.... return c; 方法可行,只是每次都得做很多次if比较
或者
map<string, ICtrl*> ctrl_; 这个方法不行,根据string返回的只是指针,没有一个新的对象
So how?C++函数指针闪亮登场,让我不得不佩服C++ is magic,You can control it all by yourself !
#pragma once#include <iostream>#include <string>#include <map>using namespace std;class ICtrl{public:virtual void Print(){cout<<"ICtrl"<<endl;}};class ILabel : public ICtrl{public:virtual void Print(){cout<<"ILabel"<<endl;}};class IButton : public ICtrl{public:virtual void Print(){cout<<"IButton"<<endl;}};inline ICtrl* NewLabel(){return new ILabel();}inline ICtrl* NewButton(){return new IButton();}typedef ICtrl* (*NewCtrl)();class CContainer{private:map<string, NewCtrl> ctrl_;public:void Register(const string class_name, NewCtrl method){ctrl_[class_name] = method;}ICtrl* operator[] (const string class_name){NewCtrl method = ctrl_[class_name];return (*method)();}};void magic_test(){CContainer magic;magic.Register("Label", &NewLabel);magic.Register("Button", &NewButton);ICtrl* c = magic["Label"];c->Print();}
- Magic C++ (函数指针)(xml配置控件样式)
- 函数指针(C++)
- C语言(函数指针)
- C语言中的指针(指针数组 数组指针 函数指针 函数指针数组 指向函数指针数组的指针)
- C程序设计语言--指针与数组(二) 指针数组 数组指针 函数指针 指针函数
- Asp.net 4.0 menu 控件样式 + XML 文件配置
- 函数指针高级运用(C函数指针)
- C、C++指向函数的指针(函数指针)浅析
- C语言入门(十九)指针函数和函数指针
- C语言中的函数指针与指针函数(续)
- C语言函数指针(指向函数的指针)
- 105 C语言函数指针(指向函数的指针)
- C/C++编程(一)--函数指针与指针函数
- PHP中的Magic Methods (魔术函数)
- CodeForce 424C Magic Formulas(数学题)
- 在rust里使用c样式的函数指针
- C语言的函数指针(42)
- C语言的指针函数(43)
- 给树莓派增加一个Linux系统调用
- java高级工程师---------spring的知识重点
- opencv(一):VC6.0下安装与配置OpenCV1.0
- 动态设置滚动条高度宽度的方法[非润乾知识库方法]
- gsensor架构和原理分析
- Magic C++ (函数指针)(xml配置控件样式)
- POJ 动态规划题目列表
- Java之美[从菜鸟到高手演变]之Java学习方法
- busybox1-17.2编译出错
- 如何在body中放frameset
- ICE Manual(Documentation for Ice 3.5)---Slice Source Files
- 移植FFMPEG到VS2008系列之三
- shell脚本中的几个括号总结(小括号/大括号/花括号)
- Windows XP系统修复功能的具体操作方法