调用模板函数时的怪异行为

Weird behaviour in calling template function

本文关键字:函数 调用      更新时间:2023-10-16

我已经编写了以下代码:

#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"的地址,但无法保证。