2011-08-12 18 views
11

क्या टेम्पलेट पर (boost) bind के साथ तर्कों को बाध्य करना संभव है?क्या मैं फ़ंक्शन टेम्पलेट के साथ बाध्य (बूस्ट) का उपयोग कर सकता हूं?

// Define a template function (just a silly example) 
template<typename ARG1, typename ARG2> 
ARG1 FCall2Templ(ARG1 arg1, ARG2 arg2) 
{ 
    return arg1 + arg2; 
} 

// try to bind this template function (and call it) 
... 
boost::bind(FCall2Templ<int, int>, 42, 56)(); // This works 

boost::bind(FCall2Templ, 42, 56)(); // This emits 5 pages of error messages on VS2005 
// beginning with: error C2780: 
// 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> 
// boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provided 

boost::bind<int>(FCall2Templ, 42, 56)(); // error C2665: 'boost::bind' : none of the 2 overloads could convert all the argument types 

विचार?

+1

इरादे, बहुरूपी व्यवहार है तो [इस] (http://stackoverflow.com/questions/7033645/is-there-a-generic-way- टू-अनुकूलन-ए-मज़ा ction-template-to-be-a-polymorphic-function) रुचि का हो सकता है। –

+0

ऐसा मत सोचो कि यह संभव है। – Arunmu

उत्तर

16

मुझे ऐसा नहीं लगता है, क्योंकि इस मामले में केवल boost::bind फ़ंक्शन पॉइंटर की तलाश में है, फ़ंक्शन टेम्पलेट नहीं। जब आप FCall2Templ<int, int> में पास करते हैं, तो संकलक फ़ंक्शन को तुरंत चालू करता है और इसे फ़ंक्शन पॉइंटर के रूप में पास किया जाता है।

लेकिन, आप कर सकते हैं, एक functor

struct FCall3Templ { 

    template<typename ARG1, typename ARG2> 
    ARG1 operator()(ARG1 arg1, ARG2 arg2) { 
    return arg1+arg2; 
    } 
}; 
int main() { 
    boost::bind<int>(FCall3Templ(), 45, 56)(); 
    boost::bind<double>(FCall3Templ(), 45.0, 56.0)(); 
    return 0; 
} 

आप वापसी प्रकार निर्दिष्ट करना का उपयोग कर वापसी प्रकार आदानों से जुड़ा हुआ है के बाद से निम्नलिखित। वापसी बदलता नहीं है, तो आप सिर्फ typedef T result_type टेम्पलेट को जोड़ सकते हैं, जिससे कि बाँध निर्धारित कर सकते हैं क्या परिणाम है

+0

यह एक साफ चाल है। बहुत बहुत धन्यवाद। – ereOn

4

यदि आप एक समारोह संदर्भ बनाने के काम करने के लिए लगता है:

int (&fun)(int, int) = FCall2Templ; 
int res2 = boost::bind(fun, 42, 56)(); 

या :

typedef int (&IntFun)(int, int); 
int res3 = boost::bind(IntFun(FCall2Templ), 42, 56)(); 

(जीसीसी पर परीक्षण किया गया)