【问题标题】:std::max cannot be resolved after including <algorithm> [duplicate]包含 <algorithm> 后无法解析 std::max [重复]
【发布时间】:2017-06-07 18:50:36
【问题描述】:

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

#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>

它神奇地编译。 (虽然实际上不应该定义一个 max 函数)

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

请注意,我也试过这个:

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

产生

error: insufficient contextual information to determine type

【问题讨论】:

  • 有多个std::max 重载。有一个需要std::initializer_list
  • 我知道这一点,但是为什么 (int(*)(int, int)) std::max 不起作用呢?
  • 试试(const int&amp; (*)(const int&amp;, const int&amp;))。那是std::max&lt;int&gt;的实际签名
  • @VolkovKomm 您在哪里看到应该有这样的过载?我的文档显示不可能 int(int,int)。
  • 哦,实际上没有 int(int, int) 重载...而且 ((const int&(*)(const int&, const int&)) 刚刚工作。我想我只是愚蠢,谢谢你的解释。

标签: c++ c++11 c++-standard-library


【解决方案1】:

这是因为同一个函数有多个重载。这不起作用的原因与它不起作用的原因完全相同

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>)};
}

【讨论】:

    【解决方案2】:

    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); };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多