STL学习:iterator

tech2022-08-31  102

iterator_traits的demo

泛型编程了解的太少,看到STL的iterator部分,了解了模板、全特化、偏特化受益匪浅,写个demo记录下。

#include<bits/stdc++.h> using namespace std; // define a class class A{ public: typedef A value_type; }; // define a trait template <class T> struct my_traits{ typedef typename T::value_type value_type; }; // specialization template<class T> struct my_traits<T *>{ typedef T value_type; }; // Override Funtion void print(int){ cout<<"int"<<endl; } void print(A){ cout<<"A"<<endl; } // template function template <class T> void extend_print(T t){ //extect the value type, then make an instance print(typename my_traits<T>::value_type()); } int main(){ int* a = new int(1); A b; extend_print<A>(b); //output: A extend_print<int*>(a); //output: int // a.type_value b; //compile wrong // A::type_value() c; //compile wrong return 0; }
最新回复(0)