Template specialization not working with char*

Viewed 48

I am trying to create a template which will add an element to the end of an array (after resizing). I want to specialize it so that if the type is char*, it will include a null byte at the end.

Here is my main:

int main()
{

    int* arrI = nullptr;
    arrI = insertAtend(arrI, 0, 1); //1
    std::cout << arrI[0];
    delete[] arrI;

    char* arrC = nullptr;
    arrC = insertAtend(arrC, 0, 'a'); //a
    std::cout << arrC;
    delete[] arrC;

    return 0;
}

And here are the templates:

template<typename T>
T* insertAtend(T* arr, int size, const T toAdd)
{
    T* temp = new T[++size];
    if (arr)
    {
        for (int i = 0; i < size; i++)
        {
            temp[i] = arr[i];
        }
        delete[] arr;
    }
    arr = new T[size + 1];
    if (temp)
    {
        for (int i = 0; i < size; i++)
        {
            arr[i] = temp[i];
        }
    }
    delete[] temp;
    arr[size - 1] = toAdd;

    return arr;
}

template<>
char* insertAtend<char*>(char* a, int s, const char* d)
{
    return a;
}

Obviously without logic, but I am getting an error:

C2912 "Error C2912 explicit specialization 'char *insertAtend<char>(char *,int,const char *)' is not a specialization of a function template"

1 Answers

You're simply confusing the base type (char) with the pointer type (char *).

Change your specialization to this:

template<>
char* insertAtend<char>(char* a, int s, const char d)
{
    return a;
}

Related