无法将 std::min 传递给函数,std::min 的副本有效 [英] Can't pass std::min to function, copy of std::min works

查看:49
本文介绍了无法将 std::min 传递给函数,std::min 的副本有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::min 传递给函数不会编译.我将 std::min 的 libcpp 声明复制到我的源文件中,它可以工作.

Passing std::min to a function does not compile. I copied the libcpp declaration of std::min into my source file and it works.

std 版本有什么问题?clang 和 gcc 也是如此.在 Godbolt 上测试:https://godbolt.org/g/zwRqUA

What's wrong with the std version? Same happens with clang and gcc. Tested on godbolt: 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 的错误:

The errors for clang and 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 为一个模板参数重载.他们是

There are two template functions min overloaded for one template parameter. They are

template<class T> constexpr const T& min(const T& a, const T& b);

template<class T>
constexpr T min(initializer_list<T> t);

所以编译器不知道选择哪一个.

So the compiler does not know which one to select.

您可以使用函数指针的显式转换来告诉编译器您指的是哪个函数.

You could use an explicit casting of the function pointer to tell the compiler which function you mean.

或者您可以使用中间指针.例如

Or you could use an intermediate pointer. For example

const int & ( *operation )( const int &, const int & ) = std::min<int>;

然后使用指针operation代替函数std::min.

And then use the pointer operation instead of the function std::min.

这篇关于无法将 std::min 传递给函数,std::min 的副本有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆