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


C++ std::is_trivially_assignable用法及代码示例


<type_traits>头文件中提供了C++ STL的std::is_trivially_assignable模板。 C++ STL的std::is_trivally_assignable模板用于检查是否可以将类型B的值分配给类型A。它返回布尔值true或false。

头文件:

#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。
  • False:如果类型A不可分配给类型B。

下面是演示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++ program to illustrate 
// std::is_trivially_assignable 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Declare classes 
class GfG { 
}; 
  
class gfg { 
}; 
  
enum class AB:int { x, 
                      y, 
                      z }; 
  
// Driver Code 
int main() 
{ 
  
    cout << boolalpha; 
  
    // Check if class GfG is assignable to 
    // class gfg or not 
    cout << "is class GfG = class gfg? "
         << is_trivially_assignable<GfG, gfg>::value 
         << endl; 
  
    // Check if class GfG is assignable to 
    // class GfG or not 
    cout << "is class GfG = class GfG? "
         << is_trivially_assignable<GfG, GfG>::value 
         << endl; 
  
    // Check if enum class AB is assignable 
    // from class gfg or not 
    cout << "is class AB = class gfg? "
         << is_trivially_assignable<AB, gfg>::value 
         << endl; 
  
    // Check if class GfG assignable to 
    // class gfg or not 
    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/




相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 std::is_trivially_assignable in C++ with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。