std::remove_const<T> 内部是如何工作的
How does std::remove_const<T> work internally
案例一
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
案例二
如果我评论第二个版本
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
,也匹配通用 T
;int
匹配 T
但不是 const T
).
规则是如果一个类型匹配两个或多个版本,编译器必须选择更专业的那个。
这是不是模板的两个不同版本。这是一个单一的模板(你称之为第一个版本),定义了一个专业化(你称之为第二个版本)。
因此,当您使用模板时,它总是首先找到模板的定义,然后查找与您正在使用的类型签名匹配的模板的预先存在的特化和实例化。如果它找到匹配的特化(或实例化),它就会使用它。只有在没有现有的特化或实例化时,它才会实例化模板。
所以当你说 remove_const<int>
它匹配模板,但不匹配专业化,所以它实例化模板。 remove_const<const int>
匹配模板,也匹配特化,所以使用特化(也是模板,所以需要实例化,但这是次要的)。
使您的 "second version" 成为专业化而不是新模板的是名称 remove_const
.[=15= 之后的 <
..>
列表]
案例一 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
案例二 如果我评论第二个版本
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
,也匹配通用 T
;int
匹配 T
但不是 const T
).
规则是如果一个类型匹配两个或多个版本,编译器必须选择更专业的那个。
这是不是模板的两个不同版本。这是一个单一的模板(你称之为第一个版本),定义了一个专业化(你称之为第二个版本)。
因此,当您使用模板时,它总是首先找到模板的定义,然后查找与您正在使用的类型签名匹配的模板的预先存在的特化和实例化。如果它找到匹配的特化(或实例化),它就会使用它。只有在没有现有的特化或实例化时,它才会实例化模板。
所以当你说 remove_const<int>
它匹配模板,但不匹配专业化,所以它实例化模板。 remove_const<const int>
匹配模板,也匹配特化,所以使用特化(也是模板,所以需要实例化,但这是次要的)。
使您的 "second version" 成为专业化而不是新模板的是名称 remove_const
.[=15= 之后的 <
..>
列表]