// 工业级模板元编程库示例 namespace meta { // 类型特性 template<typename T> structis_integral { staticconstexprbool value = false; }; template<> structis_integral<int> { staticconstexprbool value = true; }; template<> structis_integral<long> { staticconstexprbool value = true; }; // ... 其他整数类型 // 类型操作 template<typename T> structremove_const { using type = T; }; template<typename T> structremove_const<const T> { using type = T; }; template<typename T> usingremove_const_t = typename remove_const<T>::type; // 编译期算法 template<int N> structfactorial { staticconstexprint value = N * factorial<N-1>::value; }; template<> structfactorial<0> { staticconstexprint value = 1; }; };
6.2 模板参数验证
1 2 3 4 5 6 7 8 9 10 11
// 工业级模板参数验证 template<typename T> classStrictContainer { static_assert(std::is_default_constructible_v<T>, "T must be default constructible"); static_assert(std::is_copy_constructible_v<T>, "T must be copy constructible"); static_assert(std::is_destructible_v<T>, "T must be destructible");
public: StrictContainer() = default; // ... };
6.3 性能分析
1 2 3 4 5 6 7 8 9 10 11 12
// 模板性能分析工具集成 template<typename T> doublebenchmark(){ auto start = std::chrono::high_resolution_clock::now(); // 执行模板操作 T obj; obj.process(); auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration<double>(end - start).count(); }
常见模板编程错误
1. 模板参数推导失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 错误:无法推导T的类型 template<typename T> voidprint(T a, T b){ std::cout << a << " " << b << std::endl; }
print(10, 3.14); // 一个是int,一个是double
// 解决方案1:显式指定模板参数 print<double>(10, 3.14);
// 解决方案2:使用两个模板参数 template<typename T1, typename T2> voidprint(T1 a, T2 b){ std::cout << a << " " << b << std::endl; }
2. 模板实例化错误
1 2 3 4 5 6 7
// 错误:std::string没有<运算符的重载(实际上有,这里只是示例) template<typename T> T max(T a, T b){ return a > b ? a : b; }