对于auto stdMaxInt = std :: max <int>,类型推断失败;

Tob*_*ann 6 c++ function-templates auto type-deduction template-instantiation

使用GCC 4.8.4 g++ --std=c++11 main.cpp输出以下错误

error: unable to deduce ‘auto’ from ‘max<int>’
auto stdMaxInt = std::max<int>;
Run Code Online (Sandbox Code Playgroud)

这个代码

#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);
}
Run Code Online (Sandbox Code Playgroud)

为什么它适用myMax但不适用std::max?我们能让它与之合作std::max吗?

Wea*_*ish 5

这是因为std::max是一个重载函数,所以它不知道你想要创建指针的过载.您可以使用static_cast选择所需的过载.

auto stdMaxInt = static_cast<const int&(*)(const int&, const int&)>(std::max<int>);
Run Code Online (Sandbox Code Playgroud)