调用模板函数时的怪异行为
Weird behaviour in calling template function
我已经编写了以下代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
template <class T> T Min(T a, T b)
{
cout<<"template function: ";
if(a<b)
return a;
return b;
}
char *Min(char *a, char *b)
{
cout<<"non-template function: ";
if(strcmp(a,b)==0)
return a;
return b;
}
int main()
{
char c[]="x",d[]="y";
cout<<Min('x','y')<<endl;
cout<<Min("x","y")<<endl;
cout<<Min(c,d)<<endl;
return 0;
}
输出:
template function: x
template function: y
non-template function: y
第一个函数调用是可以的,它正在调用模板函数。但是,为什么第二个函数也在调用模板函数,而它是一个字符串常量。它不应该调用非模板函数吗???
还有为什么第二个函数调用的输出是y
,不应该是x
吗?调用字符串常量的函数和char类型的数组(尽管两者都是字符串)有什么区别?
C++中的文字具有N常量char的类型数组,该数组将衰减为指向常量char的指针,该指针无法转换为char*
。如果你想为C风格的字符串提供重载,你应该这样做:
const char *Min(const char *a, const char *b)
在C++中,比较不属于同一完整对象的指针在技术上是未定义的。在实践中,这意味着比较不平等的两个指针的结果可能会朝着这样或那样的方向发展,但这并不能保证。当选择模板时,它将比较衰减字符串文字后获得的指针的值,在这种情况下,"y"的地址恰好小于"x"的地址,但无法保证。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销