回调函数
#include <stdio.h> void fun(char* str) { printf("%s ", str); } void callback(void (*pfun)(char*), char* s) { pfun(s); } int main() { callback(fun, "hello"); return 0; }
类模板
#include <iostream> using namespace std; template<class T1,class T2> class MyClass { private: T1 t1; T2 t2; public: MyClass(T1 a, T2 b); void show(); }; template<class T1, class T2> MyClass<T1,T2>::MyClass(T1 a, T2 b):t1(a),t2(b) {} template<class T1, class T2> void MyClass<T1,T2>::show() {cout<<t1<<", "<<t2<<endl;} int main() { MyClass<int,int> c1(3, 5); MyClass<double,char> c2(5.5, 'c'); c1.show(); c2.show(); }
STL
stl标准模板库是c++对泛型编程思想的实现。stl广义上分为三类:algorithm算法、container容器、iterator迭代器,几乎所有的代码都采用模板类和模板函数的方式。在c++中stl被组织为13个头文件:algorithm、deque、functional、iterator、vector、list、map、memory、numeric、queue、set、statck、utility。
algorithm:
container:又称collection集合
iterator:是一种允许检查容器内元素,并实现元素遍历的数据类型
生产者消费者(linux c)
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct node { int id; struct node *next; } *head = NULL; void cleanup_handler(void* arg) { printf("cleanup handler. "); free(arg); (void)pthread_mutex_unlock(&mtx); } void* thread_func(void* arg) { struct node* p = NULL; pthread_cleanup_push(cleanup_handler, p); while (1) { pthread_mutex_lock(&mtx); while (head == NULL) { pthread_cond_wait(&cond, &mtx); } p = head; head = head->next; printf("get %d from queue ", p->id); free(p); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); } int main(int argc, char** argv) { pthread_t tid; int i; struct node* p; pthread_create(&tid, NULL, thread_func, NULL); for (i = 0; i < 10; i++) { p = malloc(sizeof(struct node)); p->id = i; pthread_mutex_lock(&mtx); p->next = head; head = p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("xxxxxxxxxxxxxxx "); pthread_cancel(tid); pthread_join(tid, NULL); printf("All done "); return 0; }