3
votes

I have a funtion which allocates memory to a pointer as following:

   void initializeImageBuffer(unsigned char **image, int w, int h)
   {
        if (*image != NULL)
            delete[] *image;
        *image = new unsigned char[w * h];
   }

now I want to generalize the argument type (unsigned char/int/double) using function template. Thats what I did:

 template<typename T, int, int>
 void initializeImageBuffer(T **image, int w, int h)
   {
        if (*image != NULL)
            delete[] *image;
        *image = new T[w * h];
   }

But there is an error using the function like:

    unsigned char* image;
    initializeImageBuffer(&image, 200, 200);

"There is no instance of overloading function with these argument types. The Arguments types are (unsigned char**, int, int)."

2

2 Answers

7
votes
template<typename T, int, int>

Here you declare that your template has three parameters, the type T and two unnamed ints. Since there is no way to deduce the value of the ints at the call site, you would need to provide them explicitly, along with T since you can only provide template arguments from left to right:

initializeImageBuffer<unsigned char, 42, 42>(&image, 200, 200);

However, what you most probably want is just to drop these ints, they have absolutely no use here.

template<typename T>
void initializeImageBuffer(T **image, int w, int h)
5
votes

You might confuse template parameters with function parameters. int, int in template parameter list are unnecessary here, and can't be deduced from the function invoking, that's why compiler complains.

Just remove them:

template<typename T>
void initializeImageBuffer(T **image, int w, int h)
{
    if (*image != NULL)
        delete[] *image;
    *image = new T[w * h];
}