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'.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With