模板专业不与Char合作*
我正在尝试创建一个模板,该模板将在数组的末端添加一个元素(调整大小后)。我想专业化它,以便如果类型为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只是将基本类型(
char
)与指针类型(char *
)混淆。更改您的专业化:
You're simply confusing the base type (
char
) with the pointer type (char *
).Change your specialization to this: