Jagoly
Jagoly

Reputation: 1009

Template parameter deduction for parameters not used in function call

So, I'm editing my wrapper around an OpenGL Shader Program. I'm trying to modify it to use templates for the functions to set uniforms, as they are all almost the same.

My desired end result is for the call:

aProgram.set_Fglm("uformName", glm::vec3(0, 1, 2));

To call the template function:

template<class T, void (*F)(GLint, GLsizei, const GLfloat*)>
void Shader::set_Fglm(const string& _name, const T& _value) {
    // do stuff using F()
}

with the template parameters <glm::vec3, gl::Uniform2fv>. Currently, I have in my cpp file the code:

template void Shader::set_Fglm<glm::vec3, gl::Uniform3fv>
(const string& _name, const glm::vec3& _value);

However, what currently happens is that I get a compile time error, saying that the Template parameter F can not be deduced. So, what I think I need is a way to say that, when we receive a parameter of type glm::vec3, we always want to use the same gl function.

If possible, I also wouldn't mind if, for example, I needed to call something like aProgram.set_F3glm. But if that's the case, how would I still have the implementation itself written only once. What I had before just stored an enum with each uniform that would then be checked to see what function to call, and the set function would just always take a c pointer.

Sorry if this is worded pretty terribly, but I'm not really sure what I'm doing.

Upvotes: 0

Views: 111

Answers (1)

Jarod42
Jarod42

Reputation: 217398

You may write a traits for that, something like:

template <typename T> struct DefaultF;

// Specialization
template <>
struct DefaultF<glm::vec3>
{
    static constexpr void (*Func)(GLint, GLsizei, const GLfloat*) = &gl::Uniform2fv;
};

template<class T, void (*F)(GLint, GLsizei, const GLfloat*) = DefaultF<T>::Func>
void Shader::set_Fglm(const string& _name, const T& _value) {
    // do stuff using F()
}

Example

Note that you may remove template parameter F and use directly DefaultF<T>::Func in your function.

Upvotes: 2

Related Questions