问题描述
写一个通用的最小函数,我想到了两个问题。该代码可以在任何输入类型和不同的参数编号下正常工作:
Writing a general minimum function, Two questions came to my mind. The code works fine with any input type and different argument number:
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)
。
Is there a better replacement for
decltype(a+b)
? I thing there's a standard class which I can't remember, something likedecltype(std::THE_RESULT<a,b>::type)
.
该 decltype(std :: THE_RESULT< a,b> :: type)
的返回类型为 const&
还是不?
The returned type of that decltype(std::THE_RESULT<a,b>::type)
is const &
or not ?
推荐答案
( c ++ 11
):
和
不确定 const&
,但是您可以使用和(和来找出答案)。
Not sure about const&
, but you could play with std::remove_cv
and std::remove_reference
(and std::is_reference
to find out the answer).
实际上,类型支持实用程序的列表。 yourself倒自己。
In fact, here's a list of type support utilities. Knock yourself out.
这篇关于一般最小和最大-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!