is_scalar template in C++

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of std::is_scalar template in C++ STL.

is_scalar is a template which comes under <type_traits> header file. This template is used to check whether the given type T is a scalar type or not

This template is a combination of is_arithmetic, is_pointer, is_enum, is_member_pointer or is_same and checks whether either if either one is true, the result of is_scalar will also be true.

What is a scalar type in C++?

A scalar type is that object which is neither a class type nor an array type. A scalar type is a type which has inbuilt functionality for the addition operator without any overloading.

Syntax

template <class T> is_scalar;

Parameters

The template can have only parameter of type T, and check whether the given type is a scalar type or not.

Return value

It returns a Boolean value, true if the given type is a scalar type, and false if the given type is not a scalar type.

Example

Input: is_scalar<int>::value;
Output: True

Input: is_scalar<A>::value; //assuming A is an object of a class.
Output: False

Example

 Live Demo

#include <iostream>
#include <type_traits>
using namespace std;
int main() {
   class TP {
   };
   cout << boolalpha;
   cout << "checking for is_scalar: ";
   cout << "\nint(TP::*): "<< is_scalar<int(TP::*)>::value;
   cout << "\nint *: "<< is_scalar<int*>::value;
   cout << "\nbool: "<< is_scalar<bool>::value;
   cout << "\nint(int): "<< is_scalar<int(int)>::value;
   return 0;
}

Output

If we run the above code it will generate the following output −

checking for is_scalar:
int(TP::*): true
int *: true
bool: true
int(int): false

Example

 Live Demo

#include <iostream>
#include <type_traits>
using namespace std;
int main() {
   class TP {
   };
   enum class TP_1 {
      var_1,
      var_2,
      var_3,
      var4
   };
   cout << boolalpha;
   cout << "checking for is_scalar: ";
   cout << "\nTP : "<< is_scalar<int(TP)>::value;
   cout << "\nTP_1: "<< is_scalar<TP_1>::value;
   cout << "\nint[10] "<< is_scalar<int[10]>::value;
   cout << "\nint&: "<< is_scalar<int&>::value;
   cout << "\nchar&: "<< is_scalar<char&>::value;
   return 0;
}

Output

If we run the above code it will generate the following output −

checking for is_scalar:
TP : false
TP_1: true
int[10] false
int&: false
char&: false
raja
Published on 23-Mar-2020 07:45:51
Advertisements