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


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


<type_traits>頭文件中提供了C++ STL的std::is_nothrow_assignable模板。 C++ STL的std::is_nothrow_assignable模板用於檢查A是否可分配給B類型,並且眾所周知它不會引發任何異常。如果A是可分配給B的類型,則它返回布爾值true,否則返回false。

頭文件:

#include<type_traits>

模板類別:

template< class A, class B >
struct is_nothrow_assignable;

用法:

std::is_assignable<A, B>::value

參數:模板std::is_assignable接受以下參數:



  • A:它代表隱式分配參數B的參數。
  • B:它表示可分配給A的參數類型。

返回值:模板std::is_assignable返回一個布爾變量,如下所示:

  • True:如果類型A可分配給類型B。
  • False:如果類型A不可分配給類型B。

下麵是演示C++中std::is_nothrow_assignable模板的程序:

程序:

// C++ program to illustrate 
// std::is_nothrow_assignable 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Declare structures 
struct A { 
}; 
  
struct B { 
    B& operator=(const A&) noexcept 
    { 
        return *this; 
    } 
    B& operator=(const B&) 
    { 
        return *this; 
    } 
}; 
  
// Declare classes 
class GfG { 
}; 
  
class gfg { 
}; 
  
enum class AB:int { x, 
                      y, 
                      z }; 
  
// Driver Code 
int main() 
{ 
  
    cout << boolalpha; 
  
    // Check if int& is assignable to 
    // double or not 
    cout << "is int = double? "
         << is_nothrow_assignable<int&, 
                                  double>::value 
         << endl; 
  
    // Check if struct A is assignable to 
    // srtuct A or not 
    cout << "is struct A = struct A? "
         << is_nothrow_assignable<A, A>::value 
         << endl; 
  
    // Check if struct B is assignable to 
    // srtuct A or not 
    cout << "is class B = class A? "
         << is_nothrow_assignable<B, A>::value 
         << endl; 
  
    // Check if struct B is assignable to 
    // srtuct B or not 
    cout << "is class B = class B? "
         << is_nothrow_assignable<B, B>::value 
         << endl; 
  
    // Check if enum class AB is assignable 
    // from class gfg or not 
    cout << "is class AB = class gfg? "
         << is_nothrow_assignable<AB, gfg>::value 
         << endl; 
  
    // Check if class GfG assignable to 
    // class gfg or not 
    cout << "is class Gfg = class gfg? "
         << is_nothrow_assignable<GfG, gfg>::value 
         << endl; 
    return 0; 
}
輸出:
is int = double? true
is struct A = struct A? true
is class B = class A? true
is class B = class B? false
is class AB = class gfg? false
is class Gfg = class gfg? false

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




相關用法


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