首页 > 解决方案 > C++ 中的 Java 样式枚举类

问题描述

我正在尝试为类似于 Java 枚举的数据类型实现枚举类。

数据类型.h

namespace Galactose {
    class DataType {
    public:
        DataType(const std::string& a_name, const size_t a_byteSize);
        DataType(const std::string& a_name, const DataType& a_componentType, const uint32_t a_componentCount);

    private:
        inline static std::vector<DataType> s_types;

        int32_t m_ordinal;
        std::string m_name;
        size_t m_byteSize;
        const DataType& m_componentType;
        uint32_t m_componentCount;
    };

    namespace DataTypes {
        inline static const DataType FLOAT(GT_STRINGIFY(FLOAT), sizeof(float));
        inline static const DataType VECTOR2(GT_STRINGIFY(VECTOR2), FLOAT, 2);
        inline static const DataType VECTOR3(GT_STRINGIFY(VECTOR3), FLOAT, 3);
        inline static const DataType VECTOR4(GT_STRINGIFY(VECTOR4), FLOAT, 4);
    };
}

数据类型.cpp

#include "DataType.h"

namespace Galactose {
    DataType::DataType(const std::string& a_name, const size_t a_byteSize)
        : m_ordinal(int32_t(s_types.size())),
          m_name(a_name),
          m_byteSize(a_byteSize),
          m_componentType(*this),
          m_componentCount(1)
    {
        s_types.emplace_back(*this);
    }

    DataType::DataType(const std::string& a_name, const DataType& a_componentType, const uint32_t a_componentCount)
        : m_ordinal(int32_t(s_types.size())),
          m_name(a_name),
          m_byteSize(a_componentType.m_byteSize * a_componentCount),
          m_componentType(a_componentType),
          m_componentCount(a_componentCount)
    {
        s_types.emplace_back(*this);
    }
}

GT_STRINGIFY在这样的预编译头文件中定义:

#define GT_STRINGIFY(x) #x

问题是变量DataTypes被多次实例化。大概每次一次#include "DataType.h"。我希望它们只被实例化一次。

我试图改变DataTypes namespaceclassError C2059 syntax error: 'string'在每个GT_STRINGIFY.

我知道我可以检查名称是否已经存在,或者使用集合而不是向量。但我真的不想走这条路。

感谢您的时间。欢迎任何建议。

标签: c++c++17

解决方案


使用其他语言工具/技术通常不是前进的方向,所以我会向你推荐一个enum class(它是 C++ 特定的,可能是你将获得的最接近的内置东西)。 为什么枚举类比普通枚举更受欢迎?

还应该注意的是,您需要标头保护: C++ 和 C 中的标头保护基本上是这样的:

#ifndef HEADER_NAME_HPP
#define HEADER_NAME_HPP
//code
#endif

推荐阅读