I am trying to implement enum class for data types similar to Java enums.
DataType.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);
};
}
DataType.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
defined in a precompiled header like this:
#define GT_STRINGIFY(x) #x
Problem is variables in DataTypes
are instantiated multiple times. Probably once per #include "DataType.h"
. I want them to be instantiated only once.
I tried to change DataTypes
namespace
by class
but gives Error C2059 syntax error: 'string'
at each GT_STRINGIFY
.
I know I can check whether name already exist, or use set instead of vector. But I don't really want to go down this road.
Thank you for your time. Any suggestions are welcomed.