Passing std::min
函数无法编译。我复制了 libcpp 声明std::min
进入我的源文件并且它可以工作。
std 版本有什么问题? clang 和 gcc 也会发生同样的情况。在 Godbolt 上测试:https://godbolt.org/g/zwRqUA https://godbolt.org/g/zwRqUA
#include <thread>
#include <algorithm>
namespace mystd {
// declaration copied verbatim from std::min (libcpp 4.0)
template <class _Tp> inline constexpr const _Tp&
mymin(const _Tp& __a, const _Tp& __b)
{
return std::min(__a, __b);
}
}
int main()
{
std::thread thr1(std::min<int>, 2, 3); // compile error
std::thread thr2(mystd::mymin<int>, 2, 3); // works
return 0;
}
clang 和 gcc 的错误:
[x86-64 clang 5.0.0 #1] error: no matching constructor for initialization of 'std::thread'
[x86-64 gcc 7.2 #1] error: no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, int, int)'
[x86-64 gcc 7.2 #1] note: couldn't deduce template parameter '_Callable'
有两个模板函数min
为一个模板参数重载。他们是
template<class T> constexpr const T& min(const T& a, const T& b);
and
template<class T>
constexpr T min(initializer_list<T> t);
所以编译器不知道选择哪一个。
您可以使用函数指针的显式转换来告诉编译器您指的是哪个函数。
或者您可以使用中间指针。例如
const int & ( *operation )( const int &, const int & ) = std::min<int>;
然后使用指针operation
而不是函数std::min
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)