c++ - 返回值的静态模板函数特化

标签 c++ templates

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

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/

相关文章:

c++ - 推导 C++11 中 lambda 参数的类型

c++ - 检查位标志

php - 自定义帖子类型中未显示 Wordpress 自定义模板

c++ - 在需要定义时避免循环类依赖

c++ - C++ 中具有多态模板类的未知方法返回类型

调用 header 中定义的模板函数时出现 C++ 链接器错误

c++ - c++ 标准中 [dcl.constexpr]p5 的基本原理

c++ - 更简洁代码的嵌套命名空间

c++ - Stockfish 12 源代码 : Templates replacing function parameters

c++ - C++ 对象的构造函数