# 每日一博 | C++ 中泛型使用导致的膨胀问题

list<int> l1; list<string> l2;

//! code-1 struct list_int_item {     int value;     struct list_int_item *next; };  struct list_int {     struct list_int_item *head;     size_t size; };  void list_int_insert(struct list_int *p, int value); int  list_int_sort(struct list_int *p); bool list_int_empty(struct list_int *p); ...

//! code-2 struct list_string_item {     string value;     struct list_string_item *next; };  struct list_string {     struct list_string_item *head;     size_t size; };  void list_string_insert(struct list_int *p, string value); int  list_string_sort(struct list_int *p); bool list_string_empty(struct list_int *p); ...

//! code-3 #define LIST_DECLARE(TYPE) /     struct list_##TYPE##_item { /         TYPE## value; /         struct list_##TYPE##_item *next; /     }; /     /     struct list_##TYPE { /         struct list_##TYPE##_item *head; /         size_t size; /     }; /     /     void list_##TYPE##_insert(struct list_##TYPE *p, ##TYPE## value); /     int  list_##TYPE##_sort(struct list_##TYPE *p); /     bool list_##TYPE##_empty(struct list_##TYPE *p); /     ...

//! code-4  LIST_DECLARE(double)

test1.cpp，里面只有map<int, string>，但定义了m1, m2, m3。

//! code-5      map<int, string> m1;     map<int, string> m2;     map<int, string> m3;      m1.insert(std::make_pair(1, "hello"));     m2.insert(std::make_pair(1, "hi"));     m3.insert(std::make_pair(1, "lichunjun"));

test2.cpp，与test1.cpp相比，里面有三个类型：

//! code-6      map<int, string> m1;     map<int, double> m2;     map<int, int> m3;      m1.insert(std::make_pair(1, "hello"));     m2.insert(std::make_pair(1, 1.2));     m3.insert(std::make_pair(1, 44));

[hevake_lcj@Hevake tmp]\$ ll test1 test2 -rwxrwxr-x. 1 18784 Mar 19 22:01 test1 -rwxrwxr-x. 1 35184 Mar 19 22:03 test2

test2比test1大一倍，原因不用多说。

//! code-7      map<int, string*> m1;     map<int, string*> m2;     map<int, string*> m3;      m1.insert(std::make_pair(1, new string("hello")));     m2.insert(std::make_pair(1, new string("hi")));     m3.insert(std::make_pair(1, new string("lichunjun")));

//! code-8      map<int, string*> m1;     map<int, double*> m2;     map<int, int*> m3;      m1.insert(std::make_pair(1, new string("hello")));     m2.insert(std::make_pair(1, new double(1.2)));     m3.insert(std::make_pair(1, new int(44)));

-rwxrwxr-x. 1 18736 Mar 19 23:05 test1 -rwxrwxr-x. 1 35136 Mar 19 23:05 test2

//! code-9      map<int, void*> m1;     map<int, void*> m2;     map<int, void*> m3;      m1.insert(std::make_pair(1, new string("hello")));     m2.insert(std::make_pair(1, new double(1.2)));     m3.insert(std::make_pair(1, new int(44)));      cout << *static_cast<string*>(m1[1]) << endl;     cout << *static_cast<double*>(m2[1]) << endl;     cout << *static_cast<int*>(m3[1]) << endl;