gpt4 book ai didi

c++ - 为什么要调用通用模板函数?

转载 作者:行者123 更新时间:2023-11-30 03:00:42 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

template <typename T> void compare(const T&, const T&){
cout<<"T"<<endl;
}
void compare(const char*, const char*){

cout<<"const char*"<<endl;
}

int main()
{

char a[]="123";

char b[]="123";

char *p1 = a, *p2 = b;

compare(p1,p2);
return 0;
}

结果是:T

但是为什么?实例化后的模板函数可能是这样的:

比较(常量字符*&,常量字符*&)

与普通函数相同。并且应该调用普通函数!

最佳答案

这就是为什么我认为编写 T const& 优于编写 const T&

模板函数使用签名 void(char* const&, char* const&) 实例化,这比 void(char const*, char const*) 更匹配>,因为它不需要将指针从 char* 转换为 char const*

关于c++ - 为什么要调用通用模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11776349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com