當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::add_lvalue_reference用法及代碼示例

<type_traits>頭文件中提供了C++ STL的std::add_lvalue_reference模板。 C++ STL的std::add_lvalue_reference模板用於獲取引用T類型的左值引用類型。左值引用是通過在某些類型後放置“&”來形成的。右值引用是通過在某些類型後放置“ &&”來形成的。左值不能將(非常量)左值引用綁定到右值。 std::add_lvalue_reference由模板std::is_lvalue_reference::value檢查。

頭文件:

#include<type_traits>

模板類別:

template< class T >
struct add_lvalue_reference

用法:

std::is_lvalue_reference<T>::value

參數:模板std::add_lvalue_reference接受單個參數T(特質類)



下麵是在C++中演示std::add_lvalue_reference的程序:

程序1:

// C++ program to illustrate 
// std::add_lvalue_reference 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Driver Code 
int main() 
{ 
  
    // Declare lvalue of type int, int&, 
    // int&& and int* 
    typedef add_lvalue_reference<int const&>::type A; 
    typedef add_lvalue_reference<int&>::type B; 
    typedef add_lvalue_reference<int&&>::type C; 
    typedef add_lvalue_reference<int&>::type D; 
  
    cout << std::boolalpha; 
  
    // Check if A is int const& or not 
    cout << "A:" << is_same<int const&, A>::value 
         << endl; 
  
    // Check if B is int* or not 
    cout << "B:" << is_same<int*, B>::value 
         << endl; 
  
    // Check if C is int& or not 
    cout << "C:" << is_same<int&, C>::value 
         << endl; 
  
    // Check if C is int && or not 
    cout << "D:" << is_same<int&&, D>::value 
         << endl; 
  
    return 0; 
}
輸出:
A:true
B:false
C:true
D:false

程序2:

// C++ program to illustrate 
// std::add_lvalue_reference 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Driver Code 
int main() 
{ 
  
    // Declare lvalue using typename 
    using a = int; 
    using b = float; 
    using lref 
        = typename add_lvalue_reference<a>::type; 
    using rref 
        = typename add_rvalue_reference<b>::type; 
  
    cout << std::boolalpha; 
  
    // Check if the above declaration 
    // are correct or not 
    cout << "is int is lvalue? "
         << is_lvalue_reference<a>::value 
         << '\n'; 
  
    cout << "is lref is lvalue? "
         << is_lvalue_reference<lref>::value 
         << '\n'; 
  
    cout << "is float is lvalue? "
         << is_rvalue_reference<b>::value 
         << '\n'; 
    return 0; 
}
輸出:
is int is lvalue? false
is lref is lvalue? true
is float is lvalue? false

參考: http://www.cplusplus.com/reference/type_traits/add_lvalue_reference/




相關用法


注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 std::add_lvalue_reference in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。