【问题标题】:What are the differences between `typename std::remove_reference<T>` and `constexpr typename std::remove_reference<T>`?`typename std::remove_reference<T>` 和 `constexpr typename std::remove_reference<T>` 有什么区别?
【发布时间】:2020-09-15 08:08:26
【问题描述】:

根据文档(https://en.cppreference.com/w/cpp/utility/move),std::move&lt;T&gt; 的构造函数有两种,发布在下面。

这些构造函数有什么区别? 最让我困惑的是为什么在第二个构造函数中需要关键字(typename)。

我是 C++ 的新手。对于这个问题的任何提示,我将不胜感激。

template< class T >
typename std::remove_reference<T>::type&& move( T&& t ) noexcept; (since C++11)(until C++14)

template< class T >
constexpr typename std::remove_reference<T>::type&& move( T&& t ) noexcept;  (since C++14)

【问题讨论】:

    标签: c++ c++11 move c++-standard-library typename


    【解决方案1】:

    [...]std::move&lt;T&gt;...有两种构造函数...

    不,它们不是构造函数,而是std::move 的函数签名。一个在 之前(即从 开始),第二个在C++14 之后。

    第二个specifier constexpr is used,意思是

    constexpr - 指定变量或函数的值可以 出现在常量表达式中

    在这里阅读更多:What are 'constexpr' useful for?


    最让我困惑的是为什么需要关键字(typename) 第二个构造函数。

    根据cppreference.comstd::remove_reference 有一个辅助类型,因为

    template< class T >
    using remove_reference_t = typename remove_reference<T>::type;  (since C++14)
    

    因此在第二个中,它可能是

    template< class T >
    constexpr std::remove_reference_t<T>&& move( T&& t ) noexcept;
    //        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    【讨论】:

    • 为什么以前的函数签名不需要关键字typename?谢谢。
    • @sunshilong369 生成的特征类型std::remove_reference 取决于模板类型T,需要通过typename 关键字向编译器提及。在此处查看更多示例:When is the “typename” keyword necessary?
    • 你看,之前的函数签名里也有std::remove_reference,那为什么不用typename前面呢?
    • 对不起,我的眼睛骗了我。这两个里面确实有typename关键字。我的心里充满了感谢。
    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 2014-06-12
    • 2021-06-02
    • 2020-12-23
    • 2021-06-21
    • 2013-04-05
    • 2013-06-04
    • 2021-10-29
    相关资源
    最近更新 更多