c++ - 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
namespace
,class
但Error C2059 syntax error: 'string'
在每个GT_STRINGIFY
.
我知道我可以检查名称是否已经存在,或者使用集合而不是向量。但我真的不想走这条路。
感谢您的时间。欢迎任何建议。
解决方案
使用其他语言工具/技术通常不是前进的方向,所以我会向你推荐一个enum class
(它是 C++ 特定的,可能是你将获得的最接近的内置东西)。
为什么枚举类比普通枚举更受欢迎?
还应该注意的是,您需要标头保护: C++ 和 C 中的标头保护基本上是这样的:
#ifndef HEADER_NAME_HPP
#define HEADER_NAME_HPP
//code
#endif
推荐阅读
- javascript - 如何修改 ES6 类的构造函数
- json - 如何使用 Python 解析 Spark 1.6 中包含空格、额外双引号和反斜杠的格式不正确的 JSON 字符串?
- python - 如何在 tkinter 中等待多次按键?
- asp.net - Asp.net Boilerplate - 没有给出与所需形式参数相对应的参数
- php - 将授权标头传递给用户电子邮件 url
- python - 将 ZipDataSet 写入 TFRecord
- javascript - 无法在本地调试 node.js
- java - Java Date 将分钟和秒设置为 0
- ios - 在 iOS 上隐藏/清除 Stage3D 会隐藏 2D 屏幕内容 - 我怎样才能让它再次渲染 2D?
- reactjs - React-navigation:使用底部选项卡导航器时不显示标题