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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。