[template] adding 'const' does not work?

Note that the second line in main() output 1 which means the returned type is not 'const int &' but 'int &'. But only the first template is enabled now. Why it is not 'const int &'?

I got this result on VS2010. Is it a compiler error? I don't have another compiler to try out now.


//-------------------- Begin Code --------------------

template<typename T>
struct add_const_ref_impl
{
typedef T const& type;
};

//template<typename T>
//struct add_const_ref_impl<T&>
//{
// typedef T& type;
//};

template<typename U>
struct add_const_ref
{
typedef typename add_const_ref_impl<U>::type type;
};



int _tmain(int argc, _TCHAR* argv[])
{
std::cout << boost::is_same<add_const_ref<int>::type, const int&>::value << std::endl;

// the output is 1. why?
std::cout << boost::is_same<add_const_ref<int&>::type, int&>::value << std::endl;

std::cout << boost::is_same<add_const_ref<const int&>::type, const int&>::value << std::endl;

return 0;
}

//-------------------- End Code --------------------



Looking at the implementation of boost::is_same, it only takes into consideration references.
It does not look at either const-ness or volatile-ness.

Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
template <typename T, typename U>
struct is_same_impl
{
   static T t;
   static U u;

   BOOST_STATIC_CONSTANT(bool, value =
      (::boost::type_traits::ice_and<
         (sizeof(type_traits::yes_type) == sizeof(detail::is_same_tester(&t,&u))),
         (::boost::is_reference<T>::value == ::boost::is_reference<U>::value),
         (sizeof(T) == sizeof(U))
        >::value));
};


Basically this says that the types are equal iff three conditions hold:
1) T* == U* such that is_same_tester< T > is called instead of the non-template is_same_tester(...)
2) T and U either are both references or are both not references;
3) The sizes of T and U are the same.

Topic archived. No new replies allowed.