std::remove_const 如何在<T>内部工作
How does std::remove_const<T> work internally
案例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
,则匹配通用T
; int
匹配T
,但不匹配const T
)。
规则是,如果类型匹配两个或多个版本,则必须选择更专业的版本。
这是不是模板的两个不同版本。这是一个单个模板(您称为第一个版本),并定义了专业化(您称之为第二版)。
因此,当您使用模板时,它总是首先找到模板的定义,然后查找与您使用的类型签名符合类型签名的模板的先前专业和实例化。如果它找到匹配的专业化(或实例化),则使用它。只有当没有现有专业化或实例化时,才会进行模板。
因此,当您说remove_const<int>
时,它与模板匹配,但不匹配专业化,因此可以实例化模板。remove_const<const int>
匹配模板并匹配专业化,因此它使用了专业化(这也是模板,因此需要实例化,但这是次要的)。
使您的"第二版"成为专业化而不是新模板的事物是<
.. >
列表remove_const
。
相关文章:
- 将函数类成员映射到类本身内部
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- Boost Spirit,获取迭代器内部语义动作
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 内联函数中具有内部链接的全局变量
- 在函数内部的声明中初始化数组,并在外部使用它
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 卷曲bracers内部结构的声明
- 从函数角度看ID到文件路径的内部与外部映射
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- <<操作员在下面的行中工作
- 如何在pugixml中获取节点的内部XML
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- 方法内部但循环仍得到预期的不合格id错误C++
- C++:具有内部链接的正向声明常量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- libcurl 和 DNS ttl 中的内部连接管理