Open In App

is_trivial in C++

std::is_trivial function is used to check whether the given type T is a trivial class or not. It is a template declared in <type_traits> header file.

What is a Trivial Class in C++?

A trivial class type is a type whose storage is contiguous (trivially copyable) and which only supports static default initialization (trivially default constructible), either cv-qualified or not. It includes scalar types, trivial classes, and arrays of any such types. A trivial class is a class (defined with class, struct, or union) that is both trivially default constructible and trivially copyable, which implies that: 



is_trivial Declaration

template< class T >
struct is_trivial;

Parameters

Return Type

To check if the T is a trivial type, we use std::is_trivial::value member:

Note: is_trivial inherits from integral_constant as being either true_type or false_type, depending on whether T is a trivial type.



Example of is_trivial

The below C++ program illustrates the usage of the is_trivial function to determine whether each class is trivial or not.




// CPP program to illustrate is_trivial function
#include <iostream>
#include <type_traits>
using namespace std;
  
class A {
};
class B {
    B() {}
};
class C : B {
};
class D {
    virtual void fn() {}
};
  
// Driver Code
int main()
{
    cout << boolalpha;
    // Returns value in boolean type
    cout << "A: " << is_trivial<A>::value << endl;
    cout << "B: " << is_trivial<B>::value << endl;
    cout << "C: " << is_trivial<C>::value << endl;
    cout << "D: " << is_trivial<D>::value << endl;
    return 0;
}

Output
A: true
B: false
C: false
D: false

Explanation

Here, A is a class that has been passed as a parameter to the function is_trivial and it will return a value of integral constant type bool i.e. true or false.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Article Tags :
C++