如何实施 remove_reference

How to implement remove_reference

我正在学习类型特征和类型转换(修改?),所以我遇到了 std::remove_reference。我试着这样实现它:

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; };

现在用的时候:

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> : ???

我正在使用 Visual Studio 2015,它告诉我 x2x4 的类型是 <type> 那么我在这里缺少什么?

注:

  1. 我正在做 { typedef const T type } 以删除引用并保持常量...
  2. 我不知道 std::remove_reference
  3. 的 C++ 标准实现

编辑:std::remove_reference没有任何问题,我只是为了学习而这样做...

I'm doing { typedef const T type } to remove reference and keep constness...

你不需要那样做。如果您从 T& 中删除引用,其中 Tconst X,那么您将得到 const X。没有必要为此专门研究。

确实需要处理右值引用。

所以你的实现应该是:

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; };

但这并没有改变您的测试无效的事实。使用最近构建的 VC++ 我得到了更多有用的错误:

main.cpp(16): error C2734: 'x2': 'const' object must be initialized if not 'extern'
main.cpp(18): error C2734: 'x4': 'const' object must be initialized if not 'extern'

这正确地告诉您您正在尝试定义一个 const 而不给它一个值。这是不允许的,因为它会有一个不确定的(即垃圾)值,而且您无法设置它!

这与你的 remove_reference 无关,如果你这样写,你会得到同样的错误:

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

如果您初始化 const 变量,您的测试将正常运行:

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;