Question

OpenGL defines C functions to manage resources. I wrote a simple wrapper to handle them in the RAII way. Function pairs are like unsigned glCreateProgram() and void glDeleteProgram(unsigned program). However, there're function pairs which work on arrays of resources like void glGenBuffers(size_t n, unsigned* buffers) and void glDeleteBuffers(size_t n, const unsigned* buffers);. For the former I wrote a simple class to do the job, and for the latter I wrote another class which handles arrays. However, I noticed that at times I just use only one buffer or texture, where I don't have to incur the expense of a vector, I thought I'll specialize the class destructor if the release function takes a size parameterr in the beginning BUT...

template <typename T_res,
          typename T_release_func,
          T_release_func func>
struct GL_resource
{
    GL_resource(T_res name_) : name{name_}
    {
    }

    ~GL_resource()
    {
        func(name);
    }

private:
    T_res name;
};

template <typename T_res, typename FT, FT func, typename RT, typename DT>
struct GL_resource<T_res, RT (size_t, DT*), func>
{
    ~GL_resource()
    {
        func(1, name);
    }
};   

for the above SSCCE g++ barks:

error: 'RT(unsigned int, DT*)' is not a valid type for a template non-type parameter struct GL_resource

I then wrote a dummy function void release(size_t, int*) {} and rewrote the specilization as

template <typename T_res, typename FT, FT func>
struct GL_resource<T_res, decltype(release), release>
{
    ~GL_resource()
    {
        func(1, name);
    }
};

This time I got:

error: 'void(unsigned int, int*)' is not a valid type for a template non-type parameter struct GL_resource.

Can someone explain why?

Was it helpful?

Solution

Functions aren't values, so they can't be non-type template parameters; but pointers to functions can be:

template <typename T_res, typename RT, typename DT, RT (*func) (size_t, DT*)>
struct GL_resource<T_res, RT (*)(size_t, DT*), func>
{
    ~GL_resource()
    {
        func(1, name);
    }
};   

Note that functions are subject to pointer decay even when used as non-type template parameters, so FT will always be a pointer-to-function type, not a function type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top