gpt4 book ai didi

c++ - 一般最小值和最大值 - C++

转载 作者:可可西里 更新时间:2023-11-01 17:13:24 25 4
gpt4 key购买 nike

写一个通用的最小函数,我想到了两个问题。该代码适用于任何输入类型和不同的参数编号:

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 pair T1, T2 are exactly the rules for determining the return type of the ternary conditional operator where T1 and T2 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_cvstd::remove_reference (和 std::is_reference 找出答案)。

事实上,here's类型支持实用程序列表。把自己打倒。

关于c++ - 一般最小值和最大值 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16497977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com