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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With