Written by on June 6, 2020 in C++, Programming with 0 Comments

Today let us try to understand the type trait std::is_trivial<T>. This trait checks if the given type is a trivial type. For a precise definition of what trivial means, please visit the official page.

As usual, we will go through three cases:

– Primitive types

– Classes without inheritance

– Classes involving inheritance

Case-1: Primitive Types

Take a look at the example below (as in the previous post, I am using the macro CHECK(T) to save some typing). 

Primitive Types

Primitive Types

The output is:

Output From The Program

Program Output

For convenience, the expected output is shown commented alongside the code. It is interesting that lvalue and rvalue references are not considered trivial, but pointer type is.

Case-2: Classes without Inheritance

Let us look at the more interesting case involving classes. The image below shows different struct/class/union definitions.

User-defined Types

User-defined Types

Class “A” has some instance variables and a member function. However, it does not have a constructor or destructor.

struct “B” does an inline initialization of a “const” field.

struct “C” defines a constructor but no destructor.

struct “D” defines a destructor but no constructor.

struct “E” defines an instance variable of user-defined type “A”.

“EArray” is a type that maps to an array of 10 elements of “E” type.

struct “F” declares a deleted assignment operator.

Finally, “U” is a union of three different types, one of which is a user-defined type “E”.

Here is the code that checks these types:

Example Program

Example Program

What is the expected output? Here it is:

Program Output

Program Output

Case-3: Classes Involving Inheritance

Our final example uses a few classes as part of inheritance. Take a look:

Inheritance Example

Inheritance Example

Here is the output from the program:

Program Output

Program Output

The reason why “G” is not trivial is because it defines a virtual function. Since “H” derives from a trivial class “E” and adds nothing by itself, it is also a trivial type. Class “C” is not trivial and hence “I” is not trivial as well.

The above use cases cover the essential properties of is_trivial<T> trait. I hope you get the picture now.

You can download the source code from here.

Have a nice weekend!

Tags: , ,


If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *