原文地址:C++ std::underlying_type 用法及代码示例
<type_traits> 头文件中提供了 C++ STL 的 std::underlying_type 模板。 C++ STL 的std::underlying_type 模板用于获取枚举类型 T 的基础类型。
头文件
#include<type_traits>
模板类别
template <class T>
struct underlying_type;
用法
std::underlying_type<class T>::value
参数: 模板 std::underlying_type 接受单个参数 T (Trait类)。
返回值: 模板 std::underlying_type 返回枚举类型 T 的基础类型。
示例
下面是在 C++ 中演示 std::underlying_type 的程序:
// 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;
}
输出为
underlying type for 'GFG' is unsigned
underlying type for 'gfg' is int