Unable to pass std :: min to function, copy std :: min works

std::minFunction transfer does not compile. I copied the libcpp declaration std::minto my source file and it works.

What happened to the std version? The same thing 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;
}

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'
+4
source share
2 answers

There are two template functions minoverloaded for one template parameter. They are

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

and

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

Therefore, the compiler does not know which one to choose.

You can use explicit casting of a function pointer to tell the compiler which function you have in mind.

.

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

operation std::min.

+7

std::min , :

std::thread thr1([](int a, int b) { return std::min(a, b); }, 2, 3);

- , @Vlad .

+3

Source: https://habr.com/ru/post/1688721/


All Articles