Open In App

is_trivial in C++

Last Updated : 28 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  • It uses the implicitly defined default, copy and move constructors, copy and move assignments, and destructors.
  • It has no virtual members.
  • It has no non-static data members with brace- or equal- initializers.
  • Its base class and non-static data members (if any) are themselves also trivial types.

is_trivial Declaration

template< class T >
struct is_trivial;

Parameters

  • T: The type that we want to check is if it is a trivial type class or not.

Return Type

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

  • It is true if the class is trivial type.
  • False otherwise.

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.

C++




// 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.


Like Article
Suggest improvement
Share your thoughts in the comments