当我写作时
T min(T& a,T& b)
{return a<b?a:b;}
然后调用min(3,4)
,会报错。
如何实现通用最小值?
最佳答案
那是因为非 const
左值引用 ( T&
) 不能绑定(bind)到右值 ( 3
和 4
是右值,这直观地意味着它们没有对象标识)。
尝试使用对 const
的左值引用相反,哪个可以绑定(bind)到右值(毕竟,min()
函数不应该改变其参数的状态)。
此外,不要忘记 template<typename T>
如果您正在编写一个函数模板,请使用以下部分:
template<typename T> // <== Don't forget this, if you are writing a template
T min(T const& a, T const& b)
// ^^^^^ ^^^^^
{
return (a < b) ? a : b;
}
例如,考虑这个小程序:
#include <iostream>
template<typename T> // <== Don't forget this, if you are writing a template
T min(T const& a, T const& b)
// ^^^^^ ^^^^^
{
return (a < b) ? a : b;
}
int main()
{
int x = 42;
int y = 1729;
std::cout << min(x, y) << std::endl; // Passing lvalues, that would be OK also
// with your original code.
std::cout << min(42, 1729) << std::endl; // Passing rvalues, this would not be OK
// with your original code (non-const
// lvalue references cannot bind to rvalues)
}
这是一个live example .
更新:
上述解决方案只允许将相同类型的值传递给min()
,否则编译器将无法执行类型推导(如果第一个和第二个参数具有不同的类型,T
应该是什么?):
min(3.14, 42); // Huh? What is `T` here, `double` or `int`?
强制编译器为 T
使用特定类型,您可以明确指定模板参数:
min<double>(3.14, 42);
然而,这不是一个非常优雅的选择(用户每次都必须手动输入正确的模板参数)。相反,您可以让您的函数模板接受两个 模板类型参数而不是一个:
#include <type_traits>
template<typename T, typename U>
typename std::common_type<T, U>::type min(T const& a, U const& b)
{
return (a < b) ? a : b;
}
并使用 std::common_type<>
type trait(自 C++11 起可用)以确定用作返回类型的正确类型。
再一次,这是一个live example .
关于c++ - 我怎样才能实现一个通用的最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16000262/