数据不匹配,编译器无法推断模板参数

Data mismatch and compiler cannot deduce template argument

本文关键字:参数 不匹配 编译器 数据      更新时间:2023-10-16

我有这个模板函数最大

template <typename T>
T max(T a, T b) { return (a > b) ? a : b; }  

我想替换这些:

int max(int a, int b){ return (a > b) ? a : b; }
char cmax(char a, char b){ return (a > b) ? a : b; }  
unsigned int umax(unsigned int a, unsigned int b){ return (a > b) ? a : b; }  

我需要ab具有相同的类型。
但是我的代码(我从 C 移植到 C++)有这样的东西:

size_t myvar;
...
...
int i = max(myvar,5);  

VS2015输出:

Error   C2672   'max': no matching overloaded function found    
Error   C2672   'max': no matching overloaded function found
Error   C2782   'T max(T,T)': template parameter 'T' is ambiguous
Error   C2784   'T max(T,T)': could not deduce template argument for 'T' from 'int'

好吧,我可能应该把5投给size_t.

我的问题是:为什么C允许这样做?更重要的是,引擎盖下会发生什么?编译器是将 5 转换为 size_t 还是什么?这样做会有什么后果?

谢谢:)

在你调用max的C代码中,两个参数都被隐式转换为类型int,因为函数的参数类型为int。因此,myvar被转换为int(转换为size_t不是5)。应避免从size_tint的转换,因为它通常会缩小(size_t通常比int长)。

在 C++14 中,您可以编写一个 max 模板,该模板可以采用两个不同类型的参数,如下所示:

template <class T, class U>
auto max(T a, U b) {
    return (a > b) ? a : b;
}

在 C++11 中,解决方案稍微冗长一些:

template <class T, class U>
typename std::common_type<T, U>::type max(T a, U b) {
    return (a > b) ? a : b;
}

返回类型将是三元表达式具有的任何类型。对于两个不同大小的整数类型,将选择较长的类型,因此不会丢失任何信息。(如果一种类型是有符号的,而另一种类型是无符号的,并且两者的长度相同,则某些信息可能会丢失。