模板专业化与CV和REF类型

问题描述 投票:2回答:1

为了了解元编程我创建了一个简单的例子:

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
1个回答
1
投票
template <class T> 
struct add_cref { 
    typedef T const& type; 
};

随着类型add_cref<int&>::typeT = int&。类型add_cref<int&>::type然后大致相同int& const &,这意味着参考int&是常量,而不是整数本身。

编辑:随着式add_cref<const int&>::typeT = const int&。类型add_cref<const int&>::type然后大致相同const int& const &,这意味着const int&是常量引用本身(第二常量由编译器忽略),但它是指一种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 &

© www.soinside.com 2019 - 2024. All rights reserved.