Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional C++11 strange behavior

Why this line doesn't compile:

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

But this works fine:

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

It would seem that function class is flexible and comfortable replacement for function pointers. But why this case doesn't work?

EDIT. My code:

#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

like image 825
Nikita Sivukhin Avatar asked Aug 28 '15 10:08

Nikita Sivukhin


1 Answers

The assignment to

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

also casts the min<int> to a particular signature. The cast to std::function does not.

Add

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

to the std::function assignment to get it to work.

auto* min_ptr = min<int>;

also fails to work.

There is more than one overload of min<int> to consider.

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.

like image 142
Yakk - Adam Nevraumont Avatar answered Sep 26 '22 08:09

Yakk - Adam Nevraumont