当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。