【发布时间】:2018-07-18 02:07:05
【问题描述】:
我正在寻找使用模板创建具有强类型的通用顶点数据容器。部分界面如下所示:
template <VertexFormat VF>
class VertexData
{
public:
template<uint32_t I>
(StronglyTypedVertex*) vertices();
};
其中 VertexFormat 是一个枚举,I 是不同数据流的索引,StronglyTypedVertex 是结果顶点数据。给定顶点数据存储为两个独立的位置流和纹理坐标(枚举VertexFormat::Pos3_TexCoord2),使用上面的顶点数据容器将如下所示:
VertexData<VertexFormat::Pos3_TexCoord2> vertexData;
Vector3* positions = vertexData.vertices<0>();
Vector2* texCoords = vertexData.vertices<1>();
这似乎是类型特征可以解决的问题。我已经设法使用具有 2 个属性的平面类型特征来实现某些工作,如下所示:
template<VertexFormat VF, uint32_t I>
struct VertexTraits
{
};
template<>
struct VertexTraits<VertexFormat::Pos3_TexCoords2, 0>
{
using Type = Vector3;
};
template<>
struct VertexTraits<VertexFormat::Pos3_TexCoords2, 1>
{
using Type = Vector2;
};
然后,VertexData::vertices 的签名变为:
template<uint32_t I>
VertexTraits<VF, I>::Type* vertices();
但是,这并不像我想的那么方便,因为顶点格式和流索引的每个排列都需要自己的类型特征特化。我希望能够在其中包含所有流的单个顶点特征,如下所示:
template<>
struct VertexTraits<VertexFormat::Pos3_TexCoords2>
{
using Stream0Type = Vector2; // Or some other similar declaration
using Stream1Type = Vector3;
};
我尝试过在 VertexTrait 中使用 Stream 特征嵌套特征类型,并尝试通过 CRTP 使用继承,但对于这两种情况,我都无法获得完全正确的语法。什么方法可以解决这个问题?如果使用未定义的流(即:上例中的 Stream2Type),是否可以通过引入静态断言或编译时错误的方式完成?
【问题讨论】:
标签: c++ templates c++14 typetraits