这就是我想为最终用户实现的:
auto spherePos = Primitive::createSphere<VertexPosition>();
auto spherePosNormTex = Primitive::createSphere<VertexPositionNormalTexture>();
基本上,我希望最终用户通过将顶点类型作为参数传递来定义他想要的图元的顶点类型。
我有一个像这样的模板化网格类:
template<typename VertexType>
class Mesh
{
std::vector<VertexType> _vertices;
...
}
我希望上面的函数根据传递给函数的模板参数返回一个 Mesh。
但我很难构建这些功能,这就是我一直在尝试的:
class Primitive
{
template<typename VertexType>
static Mesh<VertexType> createSphere();
// specialization for the position only sphere
template<>
static Mesh<VertexPosition> createSphere<VertexPosition>(){ ... }
}
但这给了我:“非命名空间范围内的显式特化”,所以我尝试了结构特化方式:
class Primitive
{
template<typename VertexType>
struct Sphere
{
static Mesh<VertexType> create();
}
template<>
struct Sphere<VertexPosition>
{
static Mesh<Position> create(){ ... }
}
template<typename T>
static Mesh<T> createSphere(){ return Sphere<T>::create(); }
}
但这又给了我同样的错误:“非命名空间范围内的显式特化”,两种方式都使用 gcc 4.8
有什么我想念的吗?还有另一种方法我应该这样做吗? 我知道我可以在函数上使用某种标志参数,但我认为模板方式对于最终用户来说看起来更简洁。
最佳答案
专门化成员函数很好。但是,要这样做,您不能直接在类里面进行。尝试
class Primitive
{
public:
template<typename VertexType>
static Mesh<VertexType> createSphere();
};
// specialization for the position only sphere
template<>
Mesh<VertexPosition> Primitive::createSphere<VertexPosition>(){ return Mesh<VertexPosition>(); }
关于c++ - 返回值的静态模板函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19430218/