简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM