为了理解元编程,我创建了一个简单的示例:
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;
结果为:true,false,true,true
当我取消注释模板规范时,结果符合预期(全部为true)
我的问题是,如果在没有注释的情况下都使用特殊化,为什么没有特殊化的第二个为假而最后一个为真。
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
。其结果是,在type
中T const&
变int const &
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句