c++ - 带有 cv 和 ref 类型的模板特化
问题描述
为了理解元编程,我创建了一个简单的示例:
template <class T> struct add_cref { typedef T const& type; };
// template <class T> struct add_cref<T&> { typedef T const& type; };
std::cout << std::boolalpha
<< std::is_same<add_cref<int>::type, int const&>::value << std::endl
<< std::is_same<add_cref<int&>::type, int const&>::value << std::endl
<< std::is_same<add_cref<const int>::type, int const&>::value << std::endl
<< std::is_same<add_cref<int const&>::type, int const&>::value << std::endl;
结果是:真,假,真,真
当我取消注释模板规范时,结果如预期(全部为真)
我的问题是,当两者都在未注释时使用专业化时,为什么第二个是假的而最后一个是真的没有专业化。
解决方案
template <class T>
struct add_cref {
typedef T const& type;
};
与类型add_cref<int&>::type
, T = int&
。然后类型add_cref<int&>::type
与 大致相同int& const &
,这意味着引用int&
是 const 而不是整数本身。
编辑:使用类型add_cref<const int&>::type
, T = const int&
。然后类型add_cref<const int&>::type
与 大致相同const int& const &
,这意味着引用本身const int&
是 const (第二个 const 被编译器忽略)但它引用 a const int
。这意味着add_cref<const int&>::type
必须是const int&
,即使没有专业化。
专业化:
template <class T>
struct add_cref<T&> {
typedef T const& type;
};
因为add_cref<int&>
既然在这个专精T&=int&
那里T=int
。结果,type
的T const&
变为int const &
。
推荐阅读
- javascript - 子数组为空时树显示展开符号
- android - 在 Flutter 应用程序中检测来自麦克风的声音字节暂停
- javascript - 本地存储数据未保存
- c++ - 使用 exe 或 DLL 从另一个程序调用程序
- unit-testing - Sonarqube 对 Spring Boot gradle 项目的覆盖率为 0%
- encryption - 在客户端加密请求
- reactjs - react-table 单元格链接不呈现组件
- javascript - 为什么我不能在 yarn add 中添加 postgresql pg?
- flutter - 创建 AppBar 作为类颤振
- c# - .net core web api 控制器生命周期