资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

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

成都创新互联专注于企业全网营销推广、网站重做改版、甘谷网站定制设计、自适应品牌网站建设、成都h5网站建设商城网站制作、集团公司官网建设、外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为甘谷等各大城市提供网站开发制作服务。

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

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

#include 
#include 

template struct is_lvalue : std::false_type {};
template struct is_lvalue : std::true_type {};

template struct is_xvalue : std::false_type {};
template struct is_xvalue : std::true_type {};

template struct is_glvalue : std::integral_constant::value || is_xvalue::value> {};
template struct is_prvalue : std::integral_constant::value> {};
template struct is_rvalue : std::integral_constant::value> {};

struct A
{
    int x = 1;
};

int main()
{
    A a;

    std::cout << std::boolalpha
    << is_lvalue::value << std::endl
    << is_glvalue::value << std::endl
    << is_xvalue::value << std::endl
    << is_rvalue::value << std::endl
    << is_prvalue::value << std::endl
    << std::endl
    << is_lvalue::value << std::endl
    << is_glvalue::value << std::endl
    << is_xvalue::value << std::endl
    << is_rvalue::value << std::endl
    << is_prvalue::value << std::endl
    << std::endl
    << is_lvalue::value << std::endl
    << is_glvalue::value << std::endl
    << is_xvalue::value << std::endl
    << is_rvalue::value << std::endl
    << is_prvalue::value << std::endl
    << std::endl
    << is_lvalue::value << std::endl
    << is_glvalue::value << std::endl
    << is_xvalue::value << std::endl
    << is_rvalue::value << std::endl
    << is_prvalue::value << std::endl
    ;
}

输出

true
true
false
false
false

true
true
false
false
false

false
false
false
true
true

false
true
true
true
false

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


分享文章:C++ 利用模板偏特化和 decltype(()) 识别表达式的值类别
网站路径:http://cdkjz.cn/article/dsogoic.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220