我正在尝试为竞争性编程竞赛编写自己的库,我需要这样的代码:
#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
答案 0 :(得分:6)
这是因为同一功能有多个重载。这不起作用的原因完全相同
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>)};
}
答案 1 :(得分:3)
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); };