gpt4 book ai didi

c++ - 如何实现 remove_reference

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:20 26 4
gpt4 key购买 nike

我正在学习类型特征和类型转换(修改?),所以我遇到了 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,它告诉我 x2 的类型和 x4<type>那我在这里错过了什么?

注意:

  1. 我在做{ typedef const T type }删除引用并保持常量...
  2. 我不知道 std::remove_reference 的 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;

关于c++ - 如何实现 remove_reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com