std::max在包含<algorithm>后无法解析
std::max cannot be resolved after including <algorithm>
我正在尝试为竞争性编程竞赛编写自己的库,我需要这样的代码:
#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); };
相关文章:
- EASTL矢量<向量<int>>连续的
- C++ <algorithm> 使用对象作为比较定义的 sort()
- TicTacToe with MiniMax algorithm 4x4
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- is_permutation方法从 #include<algorithm> 显示错误的输出
- 设置::查找和查找之间的性能差异<algorithm>
- Stringholics algorithm
- Next_Permutation algorithm
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 我不使用<algorithm>标题,但 sort() 可用
- std::max在包含<algorithm>后无法解析
- C 字符串比较“祝您好运”&gt;“再见”
- <algorithm> 定义宏 X 吗?
- 在 C++ <algorithm>中查找函数
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 我可以打电话给<algorithm>空旷的设施吗?
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 是否需要使用 - &gt;运算符在C 中调用成员函数时