剛剛看到一篇 C++ 博客,里面講到用模板偏特化和 decltype() 識別值類別:lvalue glvalue xvalue rvalue prvalue,依照博客的方法試了一下,發現根本行不通,之后,我查閱了一下 cppreference.com 關于 decltype 關鍵字的描述,發現了 decltype((運算式)) 具有以下特性:
- 如果 運算式 的值類別是亡值,
decltype將會產生T&&; - 如果 運算式 的值類別是左值,
decltype將會產生T&; - 如果 運算式 的值類別是純右值,
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
本文來自博客園,作者:mkckr0,轉載請注明原文鏈接:https://www.cnblogs.com/mkckr0/p/15820723.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/415911.html
標籤:其他
