std::remove_const 如何在<T>内部工作

How does std::remove_const<T> work internally

本文关键字:lt 内部 工作 gt remove const std      更新时间:2023-10-16

案例1 STD :: remove_const的可能实现是

template< class T > struct remove_const          { typedef T type; };
template< class T > struct remove_const<const T> { typedef T type; };

当我使用它们

std::remove_const<int> // use the first version
std::remove_const<const int> // use the second version

案例2 如果我评论第二版

template< class T > struct remove_const          { typedef T type; };
//template< class T > struct remove_const<const T> { typedef T type; };

并使用它们

std::remove_const<int> // use the first version
std::remove_const<const int> // use the first version

在情况1中,编译器如何决定为 const int

选择第二个版本

专业化。

const T版本比通用版本更专业(因为如果类型匹配const T,则匹配通用Tint匹配T,但不匹配const T)。

规则是,如果类型匹配两个或多个版本,则必须选择更专业的版本。

这是不是模板的两个不同版本。这是一个单个模板(您称为第一个版本),并定义了专业化(您称之为第二版)。

因此,当您使用模板时,它总是首先找到模板的定义,然后查找与您使用的类型签名符合类型签名的模板的先前专业和实例化。如果它找到匹配的专业化(或实例化),则使用它。只有当没有现有专业化或实例化时,才会进行模板。

因此,当您说remove_const<int>时,它与模板匹配,但不匹配专业化,因此可以实例化模板。remove_const<const int>匹配模板并匹配专业化,因此它使用了专业化(这也是模板,因此需要实例化,但这是次要的)。

使您的"第二版"成为专业化而不是新模板的事物是< .. >列表remove_const