|
| 1 | +// 手写 type traits:主模板 + 偏特化,看穿 <type_traits> 的实现原理 |
| 2 | +// 对应文章:documents/vol4-advanced/vol1-basics-cpp11-14/04-specialization-partial.md |
| 3 | +// 编译:g++ -Wall -Wextra -std=c++20 type_traits_from_scratch.cpp -o type_traits && ./type_traits |
| 4 | +#include <iostream> |
| 5 | + |
| 6 | +// is_pointer:主模板 false,指针偏特化 true |
| 7 | +template <typename T> struct is_pointer { |
| 8 | + static constexpr bool value = false; |
| 9 | +}; |
| 10 | +template <typename T> struct is_pointer<T*> { |
| 11 | + static constexpr bool value = true; |
| 12 | +}; |
| 13 | + |
| 14 | +// is_const:主模板 false,const T 偏特化 true(注意 const T* 不算,得 T 本身是 const) |
| 15 | +template <typename T> struct is_const { |
| 16 | + static constexpr bool value = false; |
| 17 | +}; |
| 18 | +template <typename T> struct is_const<const T> { |
| 19 | + static constexpr bool value = true; |
| 20 | +}; |
| 21 | + |
| 22 | +// is_reference:主模板 false,T& / T&& 偏特化 true |
| 23 | +template <typename T> struct is_reference { |
| 24 | + static constexpr bool value = false; |
| 25 | +}; |
| 26 | +template <typename T> struct is_reference<T&> { |
| 27 | + static constexpr bool value = true; |
| 28 | +}; |
| 29 | +template <typename T> struct is_reference<T&&> { |
| 30 | + static constexpr bool value = true; |
| 31 | +}; |
| 32 | + |
| 33 | +// C++14 变量模板简写(和标准库 _v 后缀同一思路) |
| 34 | +template <typename T> constexpr bool is_pointer_v = is_pointer<T>::value; |
| 35 | + |
| 36 | +int main() { |
| 37 | + std::cout << std::boolalpha; |
| 38 | + std::cout << "is_pointer<int> = " << is_pointer<int>::value << "\n"; |
| 39 | + std::cout << "is_pointer<int*> = " << is_pointer<int*>::value << "\n"; |
| 40 | + std::cout << "is_pointer<int**> = " << is_pointer<int**>::value << "\n"; |
| 41 | + std::cout << "is_const<const int> = " << is_const<const int>::value << "\n"; |
| 42 | + std::cout << "is_const<int> = " << is_const<int>::value << "\n"; |
| 43 | + std::cout << "is_const<const int*> = " << is_const<const int*>::value |
| 44 | + << " (指针自身非 const,指向 const)\n"; |
| 45 | + std::cout << "is_const<int* const> = " << is_const<int* const>::value << " (指针自身 const)\n"; |
| 46 | + std::cout << "is_reference<int&> = " << is_reference<int&>::value << "\n"; |
| 47 | + std::cout << "is_reference<int&&> = " << is_reference<int&&>::value << "\n"; |
| 48 | + std::cout << "is_pointer_v<double> = " << is_pointer_v<double> << " (_v 简写)\n"; |
| 49 | + return 0; |
| 50 | +} |
0 commit comments