Using GCC 4.8.4 with g++ --std=c++11 main.cpp
outputs the following error
error: unable to deduce ‘auto’ from ‘max<int>’
auto stdMaxInt = std::max<int>;
for this code
#include <algorithm>
template<class T>
const T& myMax(const T& a, const T& b)
{
return (a < b) ? b : a;
}
int main()
{
auto myMaxInt = myMax<int>;
myMaxInt(1, 2);
auto stdMaxInt = std::max<int>;
stdMaxInt(1, 2);
}
Why does it work with myMax
but not with std::max
? And can we make it work with std::max
?
It's because std::max
is an overloaded function, so it doesn't know which overload you want to create a pointer to. You can use static_cast
to select the overload you want.
auto stdMaxInt = static_cast<const int&(*)(const int&, const int&)>(std::max<int>);
The static_cast
answer by @JamesRoot works, but for my taste, I'd prefer a lambda:
auto stdMaxInt = [](int const& L, int const& R) -> int const& { return std::max(L, R); };
This might have the advantage of better inline-ability when passed to algorithms (untested).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With