在C++中使用std::is_trivially_assignable进行示例
C++ STL的 std::is_trivially_assignable 模板存在于
头文件:
#include<type_traits>
模板类:
template <class A, Class B>
struct is_trivially_assignable;
语法:
std::is_trivially_assignable::value
参数:
- A: 它代表接收赋值的对象类型。
- B: 它代表提供值的对象类型。
返回值: 模板 std::is_trivially_assignable 返回布尔变量,如下所示:
- True: 如果类型A可赋值给类型B,则为True。
- False: 如果类型A不可赋值给类型B,则为False。
下面是演示C++中的 std::is_trivially_assignable 的程序:
程序1:
// C++ program to illustrate
// std::is_trivially_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;
}
};
// Driver Code
int main()
{
cout << boolalpha;
// Check if int& is assignable to
// double or not
cout << "is int = double? "
<< is_trivially_assignable<int&,
double>::value
<< endl;
// Check if struct A is assignable to
// struct A or not
cout << "is struct A = struct A? "
<< is_trivially_assignable<A, A>::value
<< endl;
return 0;
}
is int = double? true
is struct A = struct A? true
is class B = class A? false
is class B = class B? false
is class AB = class gfg? false
is class Gfg = class gfg? false
程序2:
// C++程序,用于说明std::is_trivially_assignable
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
// 声明类
class GfG {
};
class gfg {
};
enum class AB : int { x,
y,
z };
// 主函数
int main()
{
cout << boolalpha;
// 检查class GfG是否可以分配给class gfg
cout << "is class GfG = class gfg? "
<< is_trivially_assignable<GfG, gfg>::value
<< endl;
// 检查class GfG是否可以分配给自己
cout << "is class GfG = class GfG? "
<< is_trivially_assignable<GfG, GfG>::value
<< endl;
// 检查enum class AB是否可以分配给class gfg
cout << "is class AB = class gfg? "
<< is_trivially_assignable<AB, gfg>::value
<< endl;
// 检查class GfG是否可以分配给class gfg
cout << "is class Gfg = class gfg? "
<< is_trivially_assignable<GfG, gfg>::value
<< endl;
return 0;
}
is class GfG = class gfg? false
is class GfG = class GfG? true
is class AB = class gfg? false
is class Gfg = class gfg? false
参考文献: http://www.cplusplus.com/reference/type_traits/is_trivially_assignable/