How to implement remove_reference

I study type traits and type conversions (modification?), So I came across std::remove_reference. I tried to implement it as follows:

template <class T>
struct remove_reference { typedef T type; };

template <class T>
struct remove_reference<const T> { typedef const T type; };

template <class T>
struct remove_reference<T&> { typedef T type; };

template <class T>
struct remove_reference<const T&> { typedef const T type; };

Now when I use it:

remove_reference<int>::type x1;        // x1 is int : Ok
remove_reference<const int>::type x2;  // x2 is <type> : ???
remove_reference<int&>::type x3;       // x3 is int : Ok
remove_reference<const int&>::type x4; // x4 is <type> : ???

I am using Visual Studio 2015 and it tells me what type x2and x4is is <type>, so what am I missing here?

Note:

  • I do { typedef const T type }to remove the link and keep the constant ...
  • I do not know the standard implementation of the C ++ standard std :: remove_reference

Edit: There is nothing wrong with std :: remove_reference, I just do it for the sake of learning ...

+4
source share
1 answer

{ typedef const T type }, ...

. T&, T - const X, const X. .

rvalue.

, :

template <class T>
struct remove_reference { typedef T type; };

template <class T>
struct remove_reference<T&> { typedef T type; };

template <class T>
struct remove_reference<T&&> { typedef T type; };

, . V++, :

main.cpp(16): C2734: 'x2': 'const' , 'extern'
main.cpp(18): C2734: "x4": const , "extern"

, const, . , (.. ), !

remove_reference, , :

int x1;
const int x2;   // error!
int x3;
const int x4;   // error!

, :

remove_reference<int>::type x1;        // x1 is uninitialized
remove_reference<const int>::type x2 = 0;
remove_reference<int&>::type x3;       // x3 is uninitialized
remove_reference<const int&>::type x4 = 0;
+2

All Articles