I was checking some solutions of the book cpp template metaprogramming for the 1st exercise http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?CPPTM_Answers_-_Exercise_2-0
Write a unary metafunction add_const_ref that returns T if it is a reference type, and otherwise returns T const&
template<typename T>
struct add_const_ref
{
typedef typename boost::add_const<T>::type ct;
typedef typename boost::add_reference<ct>::type type;
};
I revised it with c++11:
template<typename T>
struct add_const_ref_type
{
typedef typename std::add_const<T>::type ct;
typedef typename std::add_lvalue_reference<ct>::type type;
};
i do not understand why it works with reference. I expect this will add const, i.e., change the int&
to `const int&.
int main()
{
std::cout << std::is_same<add_const_ref_type<int &>::type, int&>::value << '\n'; // print 1
std::cout << std::is_same<add_const_ref_type<int &>::type, const int&>::value << '\n'; // print 0
return 0;
}