template <typename T> //泛化 struct is_void { static const bool value = false; }; template <> //特化 struct is_void<void> { static const bool value = true; }; int main(){ std::cout<<is_void<int>::value; std::cout<<is_void<void>::value; }
#include <iostream> #include <vector> #include <list> #include <iterator> using namespace std; template<typename Iter> struct traits { using iter_type = typename iterator_traits<Iter>::iterator_category; }; template<typename Iter> struct traits<Iter*> { using iter_type = random_access_iterator_tag; }; template <typename Iter> void after_n(Iter& it, int n) { if constexpr (is_same_v<typename traits<Iter>::iter_type, random_access_iterator_tag>) { it = it + n; cout << "触发了随机访问迭代器" << endl; } else { while (n--) ++it; cout << "触发了前后迭代器" << endl; } } int main() { // 案例1:list迭代器(双向迭代器,触发逐个移动) std::list<int> lst{ 1,2,3,4,5 }; auto lstIt = lst.begin(); after_n(lstIt, 3); // 跳转到4,O(n)时间 cout << "此时list的迭代器指向的值为: " << *lstIt << endl; // 案例2:vector迭代器(随机访问,直接跳转) std::vector<int> vec{ 1,2,3,4,5 }; auto vecIt = vec.begin(); after_n(vecIt, 3); // O(1)时间 cout << "此时vector的迭代器指向的值为: " << *vecIt << endl; // 案例3:原生指针(特化后的随机访问) int arr[5]{ 1,2,3,4,5 }; int* p = arr; after_n(p, 3); // O(1)时间 cout << "此时arr的迭代器指向的值为: " << *p << endl; return 0; }
#include <iostream> // 没用上 enum 和 typedef 的 trait // 编译期判断类型是否一致 template <typename T, typename V> struct same_type { static const bool value = false; }; template <typename T> struct same_type<T, T> { static const bool value = true; }; // C++14 template <typename T, typename R> constexpr bool same_type_v = same_type<T, R>::value; int main() { std::cout << (same_type_v<int, int> ? "Is same type" :"Not the same"); std::cout << (same_type_v<int, short> ? "Is same type" :"Not the same"); }