Templates
Quick Notes
Section titled “Quick Notes”Template tạo code generic theo kiểu dữ liệu. Compiler sinh phiên bản cụ thể khi template được dùng. Template rất mạnh nhưng lỗi compile có thể dài, nên giữ interface rõ.
Syntax
Section titled “Syntax”template<typename T>T maxOf(T a, T b){ return a < b ? b : a;}Class Template
Section titled “Class Template”template<typename T>class Box{public: explicit Box(T value) : value_(value) {} const T& value() const { return value_; }
private: T value_;};Specialization
Section titled “Specialization”template<typename T>struct TypeName{ static constexpr const char* value = "unknown";};
template<>struct TypeName<int>{ static constexpr const char* value = "int";};Common Mistakes
Section titled “Common Mistakes”- Tách template definition sang
.cpplàm linker không thấy instantiation. - Viết template quá tổng quát nhưng yêu cầu operator không rõ.
- Quên
typenamekhi truy cập dependent type.
Search Keywords
Section titled “Search Keywords”templates khuôn mẫu function template class template specialization typename generic programming