std::decay

定义于头文件 <type_traits>
template< class T >
struct decay;
(C++11 起)

对类型 T 应用左值到右值、数组到指针及函数到指针隐式转换,移除 cv 限定符,并定义结果类型为成员 typedef type 。正式而言:

这些转换模仿在以值传递时,应用到所有函数参数的类型转换。

目录

成员类型

名称 定义
type 应用退化类型转换到 T 的结果

帮助类型

template< class T >
using decay_t = typename decay<T>::type;
(C++14 起)

可能的实现

template< class T >
struct decay {
private:
    typedef typename std::remove_reference<T>::type U;
public:
    typedef typename std::conditional< 
        std::is_array<U>::value,
        typename std::remove_extent<U>::type*,
        typename std::conditional< 
            std::is_function<U>::value,
            typename std::add_pointer<U>::type,
            typename std::remove_cv<U>::type
        >::type
    >::type type;
};

示例

#include <iostream>
#include <type_traits>
 
template <typename T, typename U>
struct decay_equiv : 
    std::is_same<typename std::decay<T>::type, U>::type 
{};
 
int main()
{
    std::cout << std::boolalpha
              << decay_equiv<int, int>::value << '\n'
              << decay_equiv<int&, int>::value << '\n'
              << decay_equiv<int&&, int>::value << '\n'
              << decay_equiv<const int&, int>::value << '\n'
              << decay_equiv<int[2], int*>::value << '\n'
              << decay_equiv<int(int), int(*)(int)>::value << '\n';
}

输出:

true
true
true
true
true
true

参阅

(C++20)
std::remove_cvstd::remove_reference 结合
(类模板)
隐式转换 数组到指针、函数到指针、左值到右值转换

版本历史

  • (当前 | 先前 2017年11月13日 (一) 21:21Fruderica讨论 | 贡献 . . (2,448字节) (+41). . (撤销)
  • 当前 | 先前 2017年11月13日 (一) 16:03Fruderica讨论 | 贡献 . . (2,407字节) (-116). . (撤销)
  • 当前 | 先前 2017年2月9日 (四) 08:30Fruderica讨论 | 贡献. . (2,523字节) (+658). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:12P12bot讨论 | 贡献 . . (1,865字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:39P12bot讨论 | 贡献 . . (1,865字节) (-89). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:10P12bot讨论 | 贡献 . . (1,954字节) (+185). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 11:36P12讨论 | 贡献 . . (1,769字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,769字节) (-48). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:33P12讨论 | 贡献 . . (1,817字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,817字节) (+1,817). . (Translated from the English version using Google Translate)