[英]Template specialization with cv and ref types
为了理解元编程,我创建了一个简单的例子:
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 )但它指的是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
。 结果, T const&
的type
变为int const &
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.