模板专业不与Char合作*

发布于 2025-02-09 05:45:25 字数 1136 浏览 0 评论 0原文

我正在尝试创建一个模板,该模板将在数组的末端添加一个元素(调整大小后)。我想专业化它,以便如果类型为char*,它将在末尾包含一个null字节。

这是我的主要:

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;
}

这是模板:

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;
}

显然没有逻辑,但是我遇到了一个错误:

C2912“错误C2912显式专业化'char *insertatend&lt; char&gt;(char *,int,const char *)'不是功能模板的专业化'

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下伊人醉 2025-02-16 05:45:25

您只是将基本类型(char)与指针类型(char *)混淆。

更改您的专业化:

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

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;
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文