首页 > 解决方案 > 带有 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;

结果是:真,假,真,真
当我取消注释模板规范时,结果如预期(全部为真)

我的问题是,当两者都在未注释时使用专业化时,为什么第二个是假的而最后一个是真的没有专业化。

标签: c++template-meta-programming

解决方案


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。结果,typeT const&变为int const &


推荐阅读