2012-10-25 23 views
8

कृपया निम्न कोड स्निपेट देखें। मैं ओवरलोडेड फ़ंक्शन foobar के लिए std::bind का उपयोग करना चाहता हूं। यह केवल तर्क के साथ विधि को बुलाता है।std :: बाइंड और ओवरलोडेड फ़ंक्शन

auto a2 = std::bind(static_cast<void(Client::*)(int)>(&Client::foobar), cl, 
        std::placeholders::_1); 
a2(5); 

तुम भी (, संदर्भ द्वारा cl नोट करें कि यह है बांधता है ना कि मान द्वारा) प्रदर्शन कर सकते हैं एक लैम्ब्डा कब्जा करने के साथ बंधन:

#include <functional> 
#include <iostream> 
class Client 
{ 
    public : 
    void foobar(){std::cout << "no argument" << std::endl;} 
    void foobar(int){std::cout << "int argument" << std::endl;} 
    void foobar(double){std::cout << "double argument" << std::endl;} 
}; 

int main() 
{ 
    Client cl; 
    //! This works 
    auto a1 = std::bind(static_cast<void(Client::*)(void)>(&Client::foobar),cl); 
    a1(); 
    //! This does not 
    auto a2= [&](int) 
    { 
     std::bind(static_cast<void(Client::*)(int)>(&Client::foobar),cl); 
    }; 
    a2(5); 
    return 0; 
} 
+0

आप अपने लैम्ब्डा में 'वापसी' खो रहे हैं। – ildjarn

उत्तर

11

आप अनबाउंड तर्क के लिए placeholders उपयोग करने की आवश्यकता

auto a2 = [&](int i) { cl.foobar(i); }; 
+0

धन्यवाद ecatmur, यह काम करता है। – Atul

+0

और बाय-वैल्यू कैप्चर '[&, i]' या '[=, & cl]' के साथ किया जा सकता है। – Xeo

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