2013-10-17 14 views
6

मैं यह पता लगाने की क्या एसटीडी की :: समारोह हुड के नीचे चला जाता है जब बंद साथ संयोजन में उपयोग कोशिश कर रहा हूँ। मैं अभी तक अपने सिर को लपेटने में सक्षम नहीं हूं, उदाहरण के लिए: किस कन्स्ट्रक्टर को बुलाया जा रहा है? कोई भी std :: फ़ंक्शन के प्रतिस्थापन में एक न्यूनतम ड्रॉप का एक कार्य उदाहरण पोस्ट कर सकता है जो निम्न उदाहरण में आवश्यक कार्यक्षमता का समर्थन करता है? देख आभासी Impl::operator() और स्थानीय स्तर पर परिभाषित विशेष प्रकार:C++ बंद करने और std :: समारोह

template <class F> 
struct Decomposer; 

template <class R, class A> 
struct Decomposer<R (A)> 
{ 
    typedef R return_type; 
    typedef A argument_type; 
}; 


template <class F> 
struct my_function 
{ 
    typedef typename Decomposer<F>::return_type return_type; 
    typedef typename Decomposer<F>::argument_type argument_type; 

    return_type operator() (argument_type arg) const { 
    return (*impl)(arg); 
    } 

    template <class From> 
    my_function(From &&from) 
    { 
    struct ConcreteImpl : Impl 
    { 
     typename std::remove_reference<From>::type functor; 
     ConcreteImpl(From &&functor) : functor(std::forward<From>(functor)) {} 
     virtual return_type operator() (argument_type arg) const override 
     { 
     return functor(arg); 
     } 
    }; 
    impl.reset(new ConcreteImpl(std::forward<From>(from))); 
    } 

private: 
    struct Impl { 
    virtual ~Impl() {} 
    virtual return_type operator() (argument_type arg) const = 0; 
    }; 

    std::unique_ptr<Impl> impl; 
}; 

मूल विचार अपने प्रकार जानने के बिना वास्तविक बंद स्टोर करने के लिए प्रकार विलोपन उपयोग करने के लिए है:

#include <functional> 

int main(int argc, char* argv[]) 
{ 
    int mybool = 5; 

    auto foo = [&] (int arg) { 
     return mybool * arg; 
    }; 

    std::function<int(int)> foo2 = foo; 

    int result = foo2(42); 

    return 0; 
} 
+2

एक शब्द में जादू। यह सभी टेम्पलेट-केवल कोड है, हालांकि, आप बस इसे * देख सकते हैं। –

+1

यदि आपको वह दिलचस्प लगता है, ['std :: bind'] (http://en.cppreference.com/w/cpp/utility/functional/bind) आपको सकारात्मक रूप से गड़बड़ कर देगा। – WhozCraig

+0

टेम्पलेट्स के अलावा, वहाँ बड़ी सी ++ पुस्तकालयों में से एक जोड़े को वहाँ बाहर है कि खुले स्रोत (stdlibC++ आमतौर पर libC++ आमतौर पर बजना द्वारा प्रयोग किया जाता जीसीसी द्वारा प्रयोग किया जाता है, और) है, इसलिए आप भी गैर टेम्प्लेटेड कोड देख सकते हैं। की –

उत्तर

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