std::max在包含<algorithm>后无法解析

std::max cannot be resolved after including <algorithm>

本文关键字:gt algorithm 包含 lt std max      更新时间:2023-10-16

我正在尝试为竞争性编程竞赛编写自己的库,我需要这样的代码:

#include <functional>
#include <algorithm>
template <typename T>
using binop = std::function<T (T, T)>;
int main()
{
    binop<int> op = std::max<int>;
}

不幸的是,它会产生以下错误:

error: conversion from '<unresolved overloaded function type>' to non-scalar type 'binop<int> {aka std::function<int(int, int)>}' requested

,但是当我删除行

#include <algorithm>

它神奇地编译。(尽管不应该真正定义最大函数(

问题是:如何在不删除"算法"的情况下编译代码?

请注意,我也尝试过:

binop<int> op = (int(*)(int, int)) std::max<int>;

产生

error: insufficient contextual information to determine type

这是因为相同功能有多个过载。这与完全不起作用的原因完全不起作用

void foo() {}
void foo(int) {}
void foo(double) {}
int main() {
    auto foo_ptr = &foo;
}

要使您的代码工作,您必须将功能指针施放为正确的类型,以告诉编译器您参考哪个超载

#include <algorithm>
template <typename T>
using Func_t = std::function<T(T, T)>;
int main() {
    template <typename T>
    using MaxOverload_t = const T& (*) (const T&, const T&);
    auto f1 = static_cast<MaxOverload_t<int>>(&std::max<int>);
    auto f2 = Func_t<int>{static_cast<MaxOverload_t<int>>(&std::max<int>)};
}

std::max有多个过载。即使指定模板类型也不够,因为您

template< class T > 
const T& max( const T& a, const T& b );
//and
template< class T >
T max( std::initializer_list<T> ilist );

编译器无法决定您想要哪一个。

为了解决这个问题,我们可以使用lambda并将其包裹在 max的呼叫上,例如

binop<int> op = [](const auto& lhs, const auto& rhs){ return std::max(lhs, rhs); };