Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type deduction failing for auto stdMaxInt = std::max<int>;

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?

like image 359
Tobias Hermann Avatar asked Nov 14 '15 07:11

Tobias Hermann


2 Answers

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>);
like image 133
Weak to Enuma Elish Avatar answered Nov 15 '22 05:11

Weak to Enuma Elish


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).

like image 2
TemplateRex Avatar answered Nov 15 '22 04:11

TemplateRex