简体   繁体   中英

Deducing function template parameters from template argument types

I'm currently trying to write a function which takes an STL array of any type as one of its parameters. The obvious way to write it is:

template<typename T, int count>
void setArrayBufferData(GLenum usage, const std::array<T, count>& data) {
  setArrayBufferData(usage, data.data(), sizeof(T) * count);
}

And here's the other overload which it calls just for reference

void setArrayBufferData(GLenum usage, void* data, int size) {
  glBufferData(GL_ARRAY_BUFFER, size, data, usage);
}

The function definition compiles fine. However, when I try to call it

std::array<int, 4> data;
setArrayBufferData(GL_STATIC_DRAW, data);

I get a "No matching function for call to 'setArrayBufferData'" error message. I know if I specified the template parameters in the call it would work, but I want the call to deduce them. I've tried researching template template parameters, a more generic declaration followed by an std::array specialization, and every other syntactical variation I could think of, yet I can't seem to figure out a way to get what I'm looking for. Is it even possible, and if so, what needs to be done?

template<typename T, int count>
void setArrayBufferData(GLenum usage, const std::array<T, count>& data)

is incorrect, since std::array is template<typename T, size_t N> struct array . The second parameter must be of type size_t , not int .

Also, data.data() returns const T* since data is const reference to std::array, so, try to setArrayBufferData(GLenum usage, const void* data, int size) or call it with setArrayBufferData(usage, const_cast<T*>(data.data()), sizeof(T) * count);

#include <array>

void function(const void* ptr, size_t bytes)
{
}

template<typename T, size_t count>
void function(const std::array<T, count>& array)
{
   function(array.data(), sizeof(T) * count);
}

int main()
{
   std::array<int, 4> array;
   function(array);
}

this example works fine. http://liveworkspace.org/code/2a5af492e1f4229afdd0224171854d1c

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