为什么 boost::is_same<int const&, boost::add_const<int &>::value 等于 false?

Why does boost::is_same<int const&, boost::add_const<int &>::value equal false?

本文关键字:lt int boost const value 等于 false gt add 为什么 is      更新时间:2023-10-16

我正在学习Abrahams&Gurtovoy"这实际上不在第二章中,但这是我在第一个练习(2.10,2.0)时尝试的,这让我很困惑:

#include <iostream>
#include <boost/type_traits.hpp>
std::string display(bool b)
{
  return (b ? "true" : "false");
}
int main()
{
   using namespace std;
   cout << display(boost::is_same<int const&, boost::add_const<int &>::type >::value) << "n";
     return 0;
}

输出为"false"。但是,如果我删除引用,即"int const"answers"int"。输出为"true"。

如果您尝试了与中的指针相同的操作

boost::is_same<int const *, boost::add_const<int *>::type>::value

您会发现它也是false,因为boost::add_const<int *>::type生成int *const类型,这显然与int const *不同。

从本质上讲,引用也会发生同样的事情,即boost::add_const<int &>::type是生成int &const的尝试。形式上,类型int &const在C++中是非法的-cv限定不能应用于引用本身。因此,在这种情况下,boost::add_const被设计为无操作,这意味着boost::add_const<int &>::type再次生成int &

您不能向引用添加常量,它将是int& const,这是不可能的。

就像使用typedef一样,添加限定符不是文本替换,而是对整个类型有效的操作。