[英]Template specialization with cv and ref types
In order to understand metaprogramming I created a simple example:为了理解元编程,我创建了一个简单的例子:
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;
The result is: true, false, true, true结果是:真、假、真、真
When I uncomment the template spec, the result is as expected (all true)当我取消注释模板规范时,结果如预期(全部为真)
My question is, why is the second one false and the last one true without the specialization when both use the specialization when uncommented.我的问题是,为什么在没有注释的情况下第二个是假的,而最后一个是真,而没有专业化,则两者都使用专业化。
template <class T>
struct add_cref {
typedef T const& type;
};
With the type add_cref<int&>::type
, T = int&
.使用类型
add_cref<int&>::type
, T = int&
。 The type add_cref<int&>::type
is then roughly the same as int& const &
, which means that the reference int&
is const and not the integer itself.然后类型
add_cref<int&>::type
与int& const &
大致相同,这意味着引用int&
是 const 而不是整数本身。
Edit: With the type add_cref<const int&>::type
, T = const int&
.编辑:使用类型
add_cref<const int&>::type
, T = const int&
。 The type add_cref<const int&>::type
is then roughly the same as const int& const &
, which means that the reference itself const int&
is const (the second const is ignored by the compiler) but it refers to a const int
.然后,类型
add_cref<const int&>::type
与const int& const &
大致相同,这意味着引用本身const int&
是 const (编译器忽略第二个 const )但它指的是const int
。 This means that add_cref<const int&>::type
must be const int&
, even without specialization.这意味着
add_cref<const int&>::type
必须是const int&
,即使没有专门化。
With specialization:专业化:
template <class T>
struct add_cref<T&> {
typedef T const& type;
};
For add_cref<int&>
since in this specialization T&=int&
then T=int
.对于
add_cref<int&>
因为在这个专业化中T&=int&
然后T=int
。 As a result, the type
of T const&
becomes int const &
.结果,
T const&
的type
变为int const &
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.