基本思路是得到一个存储不同类型值的unordered_map。我想要做的是为 OpenGL 统一缓冲区对象创建一个易于访问的对象。最终产品看起来像:
UBO ubo = { "Uniforms", "translation", "scale", "rotation", "enabled" };
ubo["scale"] = 0.5f;
ubo["translation"] = { 0.1f, 0.1f, 0.0f };
ubo["rotation"] = { 90.0f, 0.0f, 0.0f, 1.0f };
ubo["enabled"] = GL_TRUE;
在我的 UBO 类中,我重载了 operator[]:
struct UBOData;
class UBO
{
std::unordered_map<std::string,UBOData>
...
public:
UBOData &operator[](std::string key)
{
UBOData data = new UBOData();
dataMap.emplace(key, data);
return data;
}
const UBOData& operator[](std::string key)
{
return const_cast<UBOData&>(*this)[key];
}
};
我正在使用 UBOData 来存储不同的数据类型。鉴于 C++ 世界中什么是“正确的”,这就是我信心减弱的地方。
.
.
.
struct UBOData
{
enum ReturnType {Undefined, rInt, rFloat, rDouble};
void *value;
ReturnType type;
int &operator=(int lhs);
float &operator=(float lhs);
double &operator=(double lhs);
};
我已经截断了这个例子的类型,没有 std::array 类型。另请注意,我使用 void * 来存储值并告诉我需要重新考虑我的设计。我当然这样做了,这就是我来这里的原因:)
int &UBOData::operator=(int lhs)
{
if (type == Undefined) { type = rInt; } else { assert(type == rInt); }
value = new int(lhs);
int &rValue = *((int*)value);
return rValue;
}
float &UBOData::operator=(float lhs)
{
if (type == Undefined) { type = rFloat; }
else { assert(type == rFloat); }
value = new float(lhs);
float &rValue = *((float*)value);
return rValue;
}
double &UBOData::operator=(double lhs)
{
if (type == Undefined) { type = rDouble; }
else { assert(type == rInt); }
value = new double(lhs);
double &rValue = *((double*)value);
return rValue;
}
我试图用类型检查来包装 void* 但有没有更好的方法来获得不带 void * 的多类型映射?
注意:我在 Windows 上使用 VS2013,在 Mac 和 Linux 上使用 clang。
最佳答案
boost::variant
或 boost::any
。
如果您不能或不会使用 boost,请阅读他们所做的。
我自己会选择 variant
。
关于c++ - 在 c++(11) 中是否有更简洁的方法来复制具有多类型值的 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20086206/