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

Chr*_*ver 8 c++ boost metaprogramming

我正在研究Abrahams&Gurtovoy的"C++ Template Metaprogramming" "这实际上不是第二章,而是我在第一次练习(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;
}
Run Code Online (Sandbox Code Playgroud)

输出为"false".但是,如果我删除引用,即'int const'和'int'.输出为"true".

AnT*_*AnT 11

如果你用指针尝试相同的东西,就像在

boost::is_same<int const *, boost::add_const<int *>::type>::value
Run Code Online (Sandbox Code Playgroud)

你发现它也是假的,因为boost::add_const<int *>::type生成int *const类型,显然不一样int const *.

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


Bo *_*son 9

你不能将const添加到引用中,这将int& const是不可能的.

就像使用typedef一样,添加限定符不是文本替换,而是适用于整个类型的东西.