specialization,模板特化
阿新 • • 發佈:2021-02-04
specialization,模板特化
一、模板特化的概念
特化的對立面泛化,泛化是包羅永珍,什麼型別都可以。 特化就是給它指定一個型別的特別實現,之後有人要用此型別來使用模板,那麼就需要呼叫我這個特別的實現。
二、示例程式碼
template<class Key>
struct hash {};
//這個是語法需要的寫法
template<>
struct hash<char>{
size_t operator() (char x) const { return x; }
};
template<>
struct hash<int>{
size_t operator() (int x) const { return x; }
};
template<>
struct hash<long>{
size_t operator() (long x) const { return x; }
};
void test_specialization()
{
//當需要long型別的模板時發現呼叫的是我們自己的long特化版本
std::cout << hash<long>() (1000) << std::endl;
}