Skip to content
Related Articles

Related Articles

Improve Article

std::underlying_type in C++ with Example

  • Last Updated : 28 Jul, 2020

The std::underlying_type template of C++ STL is present in the <type_traits> header file. The std::underlying_type template of C++ STL is used to get the underlying type of enum type T.

Header File:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
#include<type_traits>

Template Class:

template <class T>
struct underlying_type;

Syntax:



std::underlying_type<class T>::value

Parameter: The template std::underlying_type accepts a single parameter T(Trait class).

Return Value: The template std::underlying_type return the underlying type of enum type T.

Below is the program to demonstrate std::underlying_type in C++:

Program:




// C++ program to illustrate
// std::underlying_type
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
  
// ENUM Class GFG
enum GFG {};
  
// Class gfg
enum class gfg : int {};
  
// Driver Code
int main()
{
    bool GFG1
        = is_same<unsigned,
                  typename underlying_type<GFG>::type>::value;
  
    bool gfg1
        = is_same<int,
                  typename underlying_type<gfg>::type>::value;
  
    cout << "underlying type for 'GFG' is "
         << (GFG1 ? "unsigned" : "non-unsigned")
         << endl;
  
    cout << "underlying type for 'gfg' is "
         << (gfg1 ? "int" : "non-int")
         << endl;
  
    return 0;
}
Output:
underlying type for 'GFG' is unsigned
underlying type for 'gfg' is int

Reference: http://www.cplusplus.com/reference/type_traits/underlying_type/




My Personal Notes arrow_drop_up
Recommended Articles
Page :