Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
is_trivial function in C++
In this article we will be discussing the working, syntax and examples of std::is_trivial template in C++ STL.
is_trivial is a template which comes under <type_traits> header file. This template is used to check whether the given type T is a trivial class or not
What is a trivial class type in C++?
We say a type as a Trivial type, when its data is stored in a contiguous manner and which accepts only static default initialization. It can include arrays of any type, classes and scalar type.
Trivial class is a class which is trivially default constructed and trivially copyable. There are some points which should be taken care while making a class as trivial −
- It must have no virtual members or virtual base class.
- No non static members.
- No Base class with non-static members
Syntax
template <class T> is_trivial;
Parameters
The template can have only parameters of type T, and check whether the given type is a trivial type class or not.
Return value
It returns a Boolean value, true if the given type is a trivial class type, and false if the given type is not a trivial class type.
Example
Input: class A {};
class B { B() {} };
class D { virtual void fn() {} };
cout<<”A: ”<<is_trivial<A>;
cout<<”B: ”<<is_trivial<B>;
cout<<”D: ”<<is_trivial<D>;
Output:
A: True
B: False
D: False
Example
#include <iostream>
#include <type_traits>
using namespace std;
class TP_1 {
};
class TP_2 {
TP_2(){
}
};
class TP_3 : TP_2 {
};
class TP_4 {
virtual void dummy() {
}
};
int main() {
std::cout << std::boolalpha; //Returns value in boolean type
std::cout << "TP_1: " << std::is_trivial<TP_1>::value << endl;
std::cout << "TP_2: " << std::is_trivial<TP_2>::value << endl;
std::cout << "TP_3: " << std::is_trivial<TP_3>::value << endl;
std::cout << "TP_4: " << std::is_trivial<TP_4>::value << endl;
return 0;
}
Output
If we run the above code it will generate the following output −
TP_1: true TP_2: false TP_3: false TP_4: false