具有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;

结果为:true,false,true,true
当我取消注释模板规范时,结果符合预期(全部为true)

我的问题是,如果在没有注释的情况下都使用特殊化,为什么没有特殊化的第二个为假而最后一个为真。

迈克尔·维克斯勒
template <class T> 
struct add_cref { 
    typedef T const& type; 
};

与类型add_cref<int&>::typeT = int&add_cref<int&>::type然后,该类型与大致相同int& const &,这意味着引用int&是const而不是整数本身。

编辑:随着类型add_cref<const int&>::typeT = 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其结果是,在typeT const&int const &

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章