【问题标题】:Data mismatch and compiler cannot deduce template argument数据不匹配和编译器无法推断模板参数
【发布时间】:2017-06-16 09:14:46
【问题描述】:

我有这个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 或什么?这会带来什么后果?

谢谢:)

【问题讨论】:

  • 请注意,您的 C 版本还有其他失败情况,可能不会生成编译警告,例如当输入大于INT_MAX

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


【解决方案1】:

在调用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;
}

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

【讨论】:

  • 我想过做你的第一个解决方案。尽管编译器警告无符号/有符号 (size_t/int) 不匹配,但您的两种解决方案都有效。谢谢你的解释!
猜你喜欢
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 2014-11-20
  • 2010-10-17
  • 1970-01-01
  • 2017-03-22
相关资源
最近更新 更多