在C++中使用示例的std :: is_nothrow_assignable
C++ STL中的 type_traits 头文件中存在 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 。
下面是演示 std :: is_nothrow_assignable 模板的C++程序:
程序:
// 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 = classgfg? "
<< 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/