【问题标题】:static template function specialization for return values返回值的静态模板函数特化
【发布时间】:2013-10-17 14:58:25
【问题描述】:

这是我想为最终用户实现的目标:

auto spherePos = Primitive::createSphere<VertexPosition>();
auto spherePosNormTex = Primitive::createSphere<VertexPositionNormalTexture>();

基本上,我希望最终用户通过将顶点类型作为参数传递来定义他想要的图元类型的顶点类型。

我有一个这样的模板化网格类:

template<typename VertexType>
class Mesh
{
    std::vector<VertexType> _vertices;
    ...
}

我希望上面的函数根据传递给函数的模板参数返回一个网格。

但我很难构建这些功能,这是我一直在尝试的:

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

我有什么遗漏吗?我应该这样做吗? 我知道我可以在函数上添加某种标志参数,但我认为模板方式对最终用户来说看起来更干净。

【问题讨论】:

  • 不要专门化你的成员; 重载它们。不幸的是,您的没有参数,因此这不会轻易发生,因为仅通过返回类型不同是不够的。 (而且你所有的结构都需要尾分号,顺便说一句)。
  • 谢谢。是的,我考虑过重载它们,但因为我没有任何参数,所以很难。我可以开始将函数命名为“createSpherePosition()”“createSpherePositionNormal()”,但不知何故,我认为它看起来比我试图实现的更丑陋(返回类型的专门化)。至于分号,类也缺少它们,我很匆忙地写了这个:p
  • +1 这个问题,顺便说一句。包含 SO 问题应该包含的所有内容、您想要实现的目标、您尝试过的内容以及您对两者的观察结果。

标签: c++ templates


【解决方案1】:

专门化成员函数很好。但是,为了做到这一点,您不能直接在课堂上进行。试试

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>(); }

【讨论】:

  • +1 这应该可以。我对第二个实现非常着迷,甚至没有回滚到原来的问题。干得好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-20
  • 2013-05-30
  • 2018-11-21
  • 2022-01-17
  • 1970-01-01
  • 2016-06-16
相关资源
最近更新 更多