C++ 编译期反射1 - 获取枚举的类型名
注意: 本人是原创, 如若发现雷同,后果自负
有时我们需要获取类型的信息. 类型名, 枚举值的名, 等等. C++ 暂时不支持编译期反射(C++ 23/26会支持), 但是我们可以自己实现, 缺点就是会拖延编译速度.
开发环境:
支持 msvc, clang 和 g++, 需要C++17以上
实现:
// enum_info.hpp
#ifndef ENUM_INFO_HPP
#define ENUM_INFO_HPP
#include <cstddef>
#include <string_view>
#include <type_traits>
namespace enum_info
{
using string_view = std::string_view;
namespace details
{
template <typename Enum_type>
constexpr auto enum_type_name() noexcept
{
// 静态断言, Enum_type 必须是枚举类型
static_assert(std::is_enum_v<Enum_type>