扫码关注官方订阅号
不同的数据单元(Node)使用同一种数据结构的实现,在程序中怎么处理最好?
业精于勤,荒于嬉;行成于思,毁于随。
enum TypeId {String, Int, Bool, /* ... */ } struct Value { TypeId type; union { char* stringValue; int intValue; bool boolValue; /* ... */ } }
这么搞可以吗?弱弱的说。
更新:
这种方法采用了“Command Pattern“,虽然和题主的要求有所出入,但是实现了接口的一致。其实也不算一个坏方法吧。
附链接:http://en.wikipedia.org/wiki/Command_pattern
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include <string> using namespace std; class ivar { public: virtual void show() = 0; virtual ~ivar(){} }; class IntVar: public ivar { public: IntVar(int i_value): value(i_value){} virtual void show() { cout << value << endl; } private: IntVar(){} int value; }; class StringVar: public ivar { public: StringVar(string i_value): value(i_value){} virtual void show() { cout << value << endl; } private: string value; }; int main() { vector<ivar*> var_list; var_list.push_back(new IntVar(3)); var_list.push_back(new StringVar("abc")); var_list.push_back(new IntVar(123)); for (int i = 0; i < (int)var_list.size(); i++) { var_list[i]->show(); } for (int i = 0; i < (int)var_list.size(); i++) { delete var_list[i]; } return 0; }
Boost Variant
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
这么搞可以吗?弱弱的说。
更新:
这种方法采用了“Command Pattern“,虽然和题主的要求有所出入,但是实现了接口的一致。其实也不算一个坏方法吧。
附链接:http://en.wikipedia.org/wiki/Command_pattern
Boost Variant