---
title: "利用模板判断模板参数类型"
author: "swimmer2000"
date: "2008-06-19T14:14:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-06-19T14:14:00Z"
id: 441507
url: "https://swimmer2000.iteye.com/blog/441507"
---

C++中可以把数据类型当成参数,类型参数可以由编译器推导出来,也可以由程序员显式指定. 下面的两个模板,就可以用来判断模板的类型参数是否为reference或者const.

template &lt;typename T&gt; struct IsReference ///Use this struct to determine if a template type is a reference { enum { VALUE = 0 }; };

template &lt;typename T&gt; struct IsReference&lt;T&&gt; { enum { VALUE = 1 }; };

template &lt;typename T&gt; struct IsReference&lt;const T&&gt; { enum { VALUE = 1 }; };

template &lt;typename T&gt; struct IsConst ///Use this struct to determine if a template type is a const type { enum { VALUE = 0 }; };

template &lt;typename T&gt; struct IsConst&lt;const T&&gt; { enum { VALUE = 1 }; };

template &lt;typename T&gt; struct IsConst&lt;const T&gt; { enum { VALUE = 1 }; };

这两个模板函数(IsReference和IsConst)聪明的地方在于,编译器会根据模板参数的类型,选 择最贴近的模板类(struct)来实例化.

使用示例: template &lt;typename T&gt; void foo() { if (IsReferenc&lt;T&gt;.VALUE) { // 类型参数T为reference } if (IsConst&lt;T&gt;.VALUE) { // 类型参数为const } }