写一个通用的最小函数,我想到了两个问题。该代码适用于任何输入类型和不同的参数编号:
namespace xyz
{
template <typename T1, typename T2>
auto min(const T1 &a, const T2 &b) -> decltype(a+b)
{
return a < b ? a : b;
}
template <typename T1, typename T2, typename ... Args>
auto min(const T1 &a, const T2 &b, Args ... args) -> decltype(a+b)
{
return min(min(a, b), args...);
}
}
int main()
{
cout << xyz::min(4, 5.8f, 3, 1.8, 3, 1.1, 9) << endl;
// ^ ^ ^
// | | |
// float double int
}
decltype(a+b)
有更好的替代品吗? ?我想有一个我不记得的标准类,比如decltype(std::THE_RESULT<a,b>::type)
.decltype(std::THE_RESULT<a,b>::type)
的返回类型是const &
还是不是?
最佳答案
std::common_type
(c++11
):
For non-specialized
std::common_type
, the rules for determining the common type between every pairT1
,T2
are exactly the rules for determining the return type of the ternary conditional operator whereT1
andT2
are the types of its second and the third operands.
和
For arithmetic types, the common type may also be viewed as the type of the (possibly mixed-mode) arithmetic expression such as
T0() + T1() + ... + Tn().
不确定const&
,但你可以玩std::remove_cv
和 std::remove_reference
(和 std::is_reference
找出答案)。
事实上,here's类型支持实用程序列表。把自己打倒。
关于c++ - 一般最小值和最大值 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16497977/