如何实现remove_reference

Lai*_*ith 5 c++ types type-traits

我正在学习类型特征和类型转换(修改?),所以我遇到了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; };
Run Code Online (Sandbox Code Playgroud)

现在当我使用它时:

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> : ???
Run Code Online (Sandbox Code Playgroud)

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

笔记:

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

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

Jon*_*ely 5

我正在{ typedef const T type }删除引用并保持常量......

你不需要这样做。T&如果您从where Tis 中删除引用,const 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; };
Run Code Online (Sandbox Code Playgroud)

但这并不能改变您的测试无效的事实。使用最新版本的 VC++ 我得到了更多有用的错误:

main.cpp(16): 错误 C2734: 'x2': 'const' 对象如果不是 'extern' 则必须初始化
main.cpp(18): 错误 C2734: 'x4': 'const' 对象如果不是 ' 则必须初始化外部'

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

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

int x1;
const int x2;   // error!
int x3;
const int x4;   // error!
Run Code Online (Sandbox Code Playgroud)

如果您初始化 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;
Run Code Online (Sandbox Code Playgroud)