Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm working through "C++ Template Metaprogramming" by Abrahams & Gurtovoy" This isn't actually in chapter two but is something I tried whilst working on the first exercise (2.10, 2.0) which is confusing me:

#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;
}

The output is 'false'. However if I remove the references, i.e. 'int const' and 'int'. The output is 'true'.

like image 200
Chris Huang-Leaver Avatar asked Jun 02 '11 16:06

Chris Huang-Leaver


2 Answers

If you tried the same thing with pointers, as in

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

you'd discover that it is also false, since boost::add_const<int *>::type generates int *const type, which is obviously not the same as int const *.

Essentially the same thing happens with references, i.e. boost::add_const<int &>::type is an attempt to generate int &const. Formally, type int &const is illegal in C++ - cv-qualification cannot be applied to the reference itself. So, boost::add_const is designed to be a no-op in this case, meaning that boost::add_const<int &>::type generates int & again.

like image 160
AnT Avatar answered Oct 19 '22 14:10

AnT


You cannot add const to a reference, it would be int& const which isn't possible.

Just like with a typedef, adding qualifiers isn't a text replacement but something that works on the entire type.

like image 30
Bo Persson Avatar answered Oct 19 '22 13:10

Bo Persson