数据不匹配,编译器无法推断模板参数
Data mismatch and compiler cannot deduce template argument
我有这个模板函数最大
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; }
我需要a
和b
具有相同的类型。
但是我的代码(我从 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_t
到int
的转换,因为它通常会缩小(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;
}
返回类型将是三元表达式具有的任何类型。对于两个不同大小的整数类型,将选择较长的类型,因此不会丢失任何信息。(如果一种类型是有符号的,而另一种类型是无符号的,并且两者的长度相同,则某些信息可能会丢失。
相关文章:
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- 为什么使用不匹配的参数调用重载函数仍然有效
- 没有函数模板的实例与我不知道为什么的参数列表匹配
- 程序告诉我,即使它们明显匹配,参数也不匹配
- 模板参数'(type)0'与'EnumValue'不匹配
- 将构造函数添加到boost.python子类导致参数不匹配错误
- LPCSTR和wchar_t问题.由于参数不匹配,导致链接器错误
- 为什么可以将std::bind分配给参数不匹配的std::函数
- C++中的默认参数不匹配
- 布尔类型的参数不匹配
- 方法调用C++/数字参数不匹配
- NULL 与模板参数不匹配?
- C++ - 模板 + 'using' 子句 - 参数不匹配错误
- c++代码中的参数不匹配错误
- QT5迁移和Boost:if.hp:宏参数不匹配错误
- 为什么函数原型中的参数数量与定义中的参数不匹配
- 为什么我的函数参数不匹配