数据不匹配和编译器无法推导出模板参数

时间:2017-01-31 03:06:32

标签: c++ templates max parameter-passing min

我有这个模板函数max

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或者是什么?这可能是什么后果?

谢谢:)

1 个答案:

答案 0 :(得分:2)

在您调用max的C代码中,两个参数都隐式转换为int类型,因为函数的参数类型为int。因此,myvar会转换为int(不是5转换为size_t)。应避免从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;
}

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