【问题标题】:How to put min and max inside a function如何将最小值和最大值放入函数中
【发布时间】:2020-01-28 12:24:06
【问题描述】:

我想做这段代码

auto f = player == color ? max : min;

playercolor 是布尔值,minmax 是 C++ 库中的标准函数。

但我收到此错误:error: overloaded function with no contextual type information

如何告诉编译器我要加载比较整数的最小值和最大值?

这里是如何重现错误:

1) 创建文件toto.cpp

2) 粘贴这个:

int main() {
   bool one = 1;
   bool zero = 0;
   auto f = one == zero ? std::min : std::max;
   return 0;
}

3) 编译它g++ toto.cpp

4) 运行它./a.out

5) 观察与上述相同的错误

【问题讨论】:

  • 请提供minimal reproducible example,但在此之前,please use search first,谢谢!
  • warning: code example with too little context
  • 您的问题有一点是不对的:minmax 不是标准库中的 函数;它们是函数模板
  • minmax 不是函数。它们是函数模板

标签: c++


【解决方案1】:

这样的?

#include <algorithm>

int main() 
{
   auto Max = [](int a, int b){return std::max(a, b);};
   auto Min = [](int a, int b){return std::min(a, b);};

   bool one = 1;
   bool zero = 0;
   auto f = one == zero ? Min : Max;
   return 0;
}

我认为编译器根本无法推断出 std::max 和 std::min 的模板参数,当你这样写时:

auto f = one == zero ? std::min : std::max;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-27
    • 2015-10-29
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2013-06-27
    相关资源
    最近更新 更多