2015-08-28 20 views
7

क्यों इस लाइन संकलित करता है नहीं:कार्यात्मक सी ++ 11 अजीब व्यवहार

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

लेकिन यह ठीक काम करता है:

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

यह प्रतीत होता है कि समारोह वर्ग समारोह के लिए लचीला और आरामदायक प्रतिस्थापन है संकेत दिए गए। लेकिन यह मामला क्यों काम नहीं करता है?

संपादित करें। मेरे कोड:

#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; 
} 

जीसीसी संस्करण 4.8.2, --std = C++ 11

+1

असली कार्यक्रम कृपया, और वास्तविक त्रुटि संदेश। 'Std ::' गायब होने जितना आसान हो सकता है। – MSalters

+1

वास्तव में, यह मेरे लिए नामस्थान std; ' –

+0

कंपाइलर, संस्करण और झंडे का उपयोग कर संकलित करता है? – Yakk

उत्तर

9

काम

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

को भी एक विशेष हस्ताक्षर करने के लिए min<int> डाले। std::function पर कास्ट नहीं है।

std::function काम करने के लिए

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

जोड़े यह काम करने के लिए मिलता है।

auto* min_ptr = min<int>; 

भी काम करने में विफल रहता है।

विचार करने के लिए min<int> के एक से अधिक अधिभार हैं।

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

सी ++ 14 में भी काम करता है।

+0

लेकिन * क्यों * किसी विशेष हस्ताक्षर के लिए std :: function cast min पर नहीं डाला जाता है? – syntagma

+0

@REACHUS इस मुद्दे को ['std :: function' constructor] (http://en.cppreference.com/w/cpp/utility/functional/function/function) सूर्य के नीचे कुछ भी लेता है। – CoffeeandCode

+0

लेकिन क्यों निश्चित प्रकार संकलक के साथ परिवर्तनीय 'min_ptr' घोषित करने के बाद स्वचालित रूप से इस प्रकार के सही तर्क नहीं डाले जा सकते हैं? –

संबंधित मुद्दे