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

标签 c++ c++11

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

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/

相关文章:

c++ - 为什么具有 const 成员的结构可以赋值?

c++ - shared_ptr 别名构造函数

c++ - 转换到同一类型

c++ - DLL 将抽象基类导出为成员函数的参数 - C++

c++ - 类成员中的 pthread_create

c++ - & 符号 '&' 参数末尾的运算符

c++ - 如何在 C++ 中获得立方根?

c++ - 不明确的模板函数重载接受可调用或值 T

c++ - C++去除字符串中连续重复的字符

c++ - 为什么大小不是 std::initializer_list 的模板参数?