找回密码
 立即注册

QQ登录

只需一步,快速开始

工控课堂 首页 工控文库 上位机编程 查看内容

C++ 利用模板偏特化和 decltype(()) 识别表达式的值类别

2022-6-27 21:56| 发布者: gk-auto| 查看: 1290| 评论: 0

摘要: 刚刚看到一篇 C++ 博客,里面讲到用模板偏特化和decltype()识别值类别:lvalueglvaluexvaluervalueprvalue。依照博客的方法试了一下,发现根本行不通。之后,我查阅了一下cppreference.com关于decltype关键字的描述 ...

刚刚看到一篇 C++ 博客,里面讲到用模板偏特化和 decltype() 识别值类别:lvalue glvalue xvalue rvalue prvalue。依照博客的方法试了一下,发现根本行不通。之后,我查阅了一下 cppreference.com 关于 decltype 关键字的描述,发现了 decltype((表达式)) 具有以下特性:

  • 如果 表达式 的值类别是 xvaluedecltype 将会产生 T&&
  • 如果 表达式 的值类别是 lvaluedecltype 将会产生 T&
  • 如果 表达式 的值类别是 prvaluedecltype 将会产生 T

也就是可以细分 xvalue 和 lvalue,于是尝试将模板偏特化和 decltype(()) 结合,发现这种方法可行。

#include <iostream>

#include <type_traits>


template<typename T> struct is_lvalue : std::false_type {};

template<typename T> struct is_lvalue<T&> : std::true_type {};


template<typename T> struct is_xvalue : std::false_type {};

template<typename T> struct is_xvalue<T&&> : std::true_type {};


template<typename T> struct is_glvalue : std::integral_constant<bool, is_lvalue<T>::value || is_xvalue<T>::value> {};

template<typename T> struct is_prvalue : std::integral_constant<bool, !is_glvalue<T>::value> {};

template<typename T> struct is_rvalue : std::integral_constant<bool, !is_lvalue<T>::value> {};


struct A

{

    int x = 1;

};


int main()

{

    A a;


    std::cout << std::boolalpha

    << is_lvalue<decltype(("abcd"))>::value << std::endl

    << is_glvalue<decltype(("abcd"))>::value << std::endl

    << is_xvalue<decltype(("abcd"))>::value << std::endl

    << is_rvalue<decltype(("abcd"))>::value << std::endl

    << is_prvalue<decltype(("abcd"))>

输出


true

true

false

false

false


true

true

false

false

false


false

false

false

true

true


false

true

true

true

false

所有的输出结果都符合预期。

关注公众号,加入500人微信群,下载100G免费资料!

最新评论

热门文章
关闭

站长推荐上一条 /1 下一条

QQ|手机版|免责声明|本站介绍|工控课堂 ( 沪ICP备20008691号-1 )

GMT+8, 2025-12-22 21:08 , Processed in 0.058039 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

返回顶部