Functional C ++ 11 weird behavior

Why this line does not compile:

function<const int&(const int&, const int&)> min_ptr = min<int>; 

But this works great:

 const int &(*min_ptr)(const int&, const int&) = min<int>; 

It would seem that a function class is a flexible and convenient replacement for function pointers. But why does this case not work?

EDIT . My code is:

 #include <functional> #include <algorithm> #include <cmath> using namespace std; int main() { const int&(*min_ptr)(const int&, const int&) = min<int>; //It is works fine function<const int&(const int &, const int&)> min_f = min<int>;// Doesn't compile /* Error message: error: conversion from '<unresolved overloaded function type>' to non-scalar type 'std::function<const int&(const int&, const int&)>' requested function<const int&(const int &, const int&)> min_f = min<int>; */ return 0; } 

gcc version 4.8.2, -std = C ++ 11

+7
c ++ pointers c ++ 11 function-pointers
source share
1 answer

Appointment

 const int &(*min_ptr)(const int&, const int&) 

also distinguishes min<int> to a specific signature. The cast to std::function not executed.

Add

  static_cast<const int &(*)(const int&, const int&)> 

to assign std::function to make it work.

 auto* min_ptr = min<int>; 

also does not work.

More than one min<int> overload is considered.

 std::function<const int&(const int &, const int&)> min_ptr = [](auto&&...args)->decltype(auto){ return min<int>(decltype(args)(args)...); }; 

also works in C ++ 14.

+9
source share

All Articles