简体   繁体   中英

static template function specialization for return values

This is what I want to achieve for the end user:

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

Basically I want the end user to define what kind of vertex type he wants for his primitive by passing the the vertex type as a parameter.

I have a templated Mesh class like this:

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

and i want the functions above to return a Mesh according to the template parameter that was passed to the function.

but im having a hard time building those functions, this is what i've been trying:

class Primitive
{
    template<typename VertexType>
    static Mesh<VertexType> createSphere();

    // specialization for the position only sphere
    template<>
    static Mesh<VertexPosition> createSphere<VertexPosition>(){ ... }
}

but this gives me: "explicit specialization in non-namespace scope", so i tried the struct specialization way:

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

But this again gives me the same error: "explicit specialization in non-namespace scope", both ways using gcc 4.8

Is there something I'm missing? is there another way I should be doing this? I know I could some kind of flag parameter on the functions, but I think the template way would look cleaner for the end user.

Specializing member functions is fine. However, in order to do so you can't do it directly in the class. Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM