C++模板特化

C++中的模板特化和泛化相对应,是特殊的泛化,例如设计一个模板类,传入的类型如果不加限制那么就是泛化,如果加以限制,只能传入固定的几种类型,那么就是特化。

模板特化示例代码:

Myhash.h文件:
#pragma once
#include <stddef.h>
template<class Key>
struct Myhash {};
template<>
struct Myhash<char>
{
 size_t operator ()(char x) const { return x; }
};
template<>
struct Myhash<int>
{
 size_t operator ()(int x) const { return x; }
};
template<>
struct Myhash<long>
{
 size_t operator ()(long x) const { return x; }
};

 

 
Myhash.cpp文件:
#include "stdafx.h"
#include "Myhash.h"

 

 
 
调用:
cout << Myhash<char>()('a') << endl;//输出为97
cout << Myhash<int>()(50) << endl;//输出为50

 

 
 
posted @ 2020-10-28 23:01  我瘦够了  阅读(159)  评论(0编辑  收藏  举报