Nov 6, 2013

[c++11][NOTE][ORIGINAL] const references in c++ templates

It is just that, for [typedef] aka. [using] in C++11
it's read from right to left, i.e

typedef int* INT;

typedef const INT const_ptr_t;
const_ptr_t is of type :

int* const

This applies to template type system as well.
Which is that:

typedef int& INT;
typedef const INT int_ref_not_really;
There is no const ref, while compiler just dump the constentness
make it to type:

int&



e.g:
template<typename T>
struct Test
{
  typedef T& type1;
  typedef T&& type2;
  typedef const T& type3;
  typedef const T&& type4;
};

Test<int>::type1; // int&
Test<int>::type2; // int&&
Test<int>::type3; // int const&
Test<int>::type4; // int const&&

/*
 Use specialize template class to deal with input T&, i.e
template<typename T>
struct Test<T&>
{
  typedef const T& type1;
};

this will capture  (C.V type&). T will be C.V type.
*/
Test<int&>::type1; // int& , int&& collapse to int&
Test<int&>::type2; // int& , int&&& collapse to int&
Test<int&>::type3; // int& , int&& collapse to int& , no const
Test<int&>::type4; // int& , int&&& collapse to int& , no const


Test<int&&>::type1; // int& , int&&& collapse to int&
Test<int&&>::type2; // int&& , int&&&& collapse to int&&
Test<int&&>::type3; // int& , int&&& collapse to int& , no const
Test<int&&>::type4; // int&& , int&&&& collapse to int&& , no const

Test<const int&>::type1; // const int& , const int&& collapse to const int&
Test<const int&>::type2; // const int& , const int&&& collapse to const int&
Test<const int&>::type3; // const int& , const int&& collapse to const int&
Test<const int&>::type4; // const int& , const int&&& collapse to const int&
Reference: const references in c++ templates

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.