我试图为竞争性的编程竞赛编写自己的库,我需要这样的代码:
#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发布于 2017-06-07 18:54:47
这是因为同一个函数有多个重载。这并不完全是因为这个不起作用的原因。
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>)};
}发布于 2017-06-07 18:56:28
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); };https://stackoverflow.com/questions/44420636
复制相似问题