Skip to content

Templates

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õ.

template<typename T>
T maxOf(T a, T b)
{
return a < b ? b : a;
}
template<typename T>
class Box
{
public:
explicit Box(T value) : value_(value) {}
const T& value() const { return value_; }
private:
T value_;
};
template<typename T>
struct TypeName
{
static constexpr const char* value = "unknown";
};
template<>
struct TypeName<int>
{
static constexpr const char* value = "int";
};
  • Tách template definition sang .cpp là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 typename khi truy cập dependent type.

templates khuôn mẫu function template class template specialization typename generic programming