C++ 利用模板偏特化和 decltype(()) 识别表达式的值类别
2022-01-20 00:43
821 查看
刚刚看到一篇 C++ 博客,里面讲到用模板偏特化和
decltype()识别值类别:
lvalue
glvalue
xvalue
rvalue
prvalue。依照博客的方法试了一下,发现根本行不通。之后,我查阅了一下 cppreference.com 关于
decltype关键字的描述,发现了
decltype((表达式))具有以下特性:
- 如果 表达式 的值类别是
xvalue
,decltype
将会产生T&&
; - 如果 表达式 的值类别是
lvalue
,decltype
将会产生T&
; - 如果 表达式 的值类别是
prvalue
,decltype
将会产生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"))>::value << std::endl << std::endl << is_lvalue<decltype((a))>::value << std::endl << is_glvalue<decltype((a))>::value << std::endl << is_xvalue<decltype((a))>::value << std::endl << is_rvalue<decltype((a))>::value << std::endl << is_prvalue<decltype((a))>::value << std::endl << std::endl << is_lvalue<decltype((A()))>::value << std::endl << is_glvalue<decltype((A()))>::value << std::endl << is_xvalue<decltype((A()))>::value << std::endl << is_rvalue<decltype((A()))>::value << std::endl << is_prvalue<decltype((A()))>::value << std::endl << std::endl << is_lvalue<decltype((A().x))>::value << std::endl << is_glvalue<decltype((A().x))>::value << std::endl << is_xvalue<decltype((A().x))>::value << std::endl << is_rvalue<decltype((A().x))>::value << std::endl << is_prvalue<decltype((A().x))>::value << std::endl ; }
输出
true true false false false true true false false false false false false true true false true true true false
所有的输出结果都符合预期。
相关文章推荐
- C++利用常量表达式在编译期操作字符串
- MFC中利用Opencv与C++抓取摄像头进行人脸识别(Mat)
- C++中利用模板求数组长度的代码
- 关于C++的模板偏特化和萃取编程技法
- C++表达式求值(利用数据结构栈)
- 利用c++模板实现单链表
- 利用C++模板,代替虚函数,实现类的静态多态性(加入性能测试部分)
- 用汇编的眼光看C++(之缺省模板、特化模板) 18
- C++ 模板的特化与偏特化
- C++模板知识->特化
- Lua 与C/C++ 交互系列:利用模板技术在Lua Code中注册C++类
- C++_利用栈进行运算符表达式的运算
- 再论c++模板之类型识别之如何得到类型信息
- C++ 模板的特化与偏特化
- C++模板编程中只特化模板类的一个成员函数
- 利用C++模板封装链表
- C++学习 【4.5】 利用函数实现指定的功能---局部变量、全局变量、变量的存储类别、声明和定义
- C++模板:究竟什么是特化?
- C++中模板的特化与偏特化
- C++利用链栈实现表达式求值