2012-08-27 17 views
5
template <class T> struct greater : binary_function <T, T, bool> { 
    bool operator() (const T& x, const T& y) const { 
     return x > y; 
    } 
}; 

मुझे एसटीएल लाइब्रेरी में "असमानता तुलना से अधिक के लिए फ़ंक्शन ऑब्जेक्ट क्लास" की परिभाषा मिली। क्या कोई मुझे बता सकता है कि यह कोड कैसे काम करता है और संकलित करता है?सी ++ "अधिक" फ़ंक्शन ऑब्जेक्ट परिभाषा

+1

के बराबर है परिभाषित करने प्रकार तक पहुंचने देता है यह क्या के बारे में ? एक उपयोग 'std :: sort (start (arr), end (arr), std :: अधिक ()) हो सकता है; 'उच्चतम से निम्नतम तक पूर्णांक के कंटेनर को सॉर्ट करने के लिए। – chris

उत्तर

4
template <class T> // A template class taking any type T 
// This class inherit from std::binary_function 
struct greater : binary_function <T, T, bool> 
{ 
    // This is a struct (not a class). 
    // It means members and inheritens is public by default 

    // This method defines operator() for this class 
    // you can do: greater<int> op; op(x,y); 
    bool operator() (const T& x, const T& y) const { 
    // method is const, this means you can use it 
    // with a const greater<T> object 
    return x > y; // use T::operator> const 
        // if it does not exist, produces a compilation error 
    } 
}; 

यहाँ std::binary_function

template <class Arg1, class Arg2, class Result> 
struct binary_function { 
    typedef Arg1 first_argument_type; 
    typedef Arg2 second_argument_type; 
    typedef Result result_type; 
}; 

की परिभाषा यह आप binary_function

greater<int> op; 
greater<int>::result_type res = op(1,2); 

जो

std::result_of<greater<int>>::type res = op(1,2); 
+0

'std :: result_of' क्या है? – 0x499602D2

+1

@ डेविड, http://en.cppreference.com/w/cpp/types/result_of – chris

+0

मैंने पढ़ा है कि टेम्पलेट पैरामीटर बंद करने के बीच एक जगह होनी चाहिए ... इसलिए '>' > '?? – 0x499602D2

0

यह एक टेम्पलेट वर्ग है जिसे एक प्रकार के तर्क के साथ तुरंत चालू किया जा सकता है। तो आप greater<int>, greater<my_class> इत्यादि कह सकते हैं। इनमें से प्रत्येक इंस्टॉलेशन में ऑपरेटर() होता है जो const T& के दो तर्क लेता है और उन्हें तुलना करने का परिणाम देता है।

greater<int> gi; 
if (gi(1, 2)) { 
    // won't get here 
} else { 
    // will get here 
} 
0

मुझे नहीं पता कि आप टेम्पलेट प्रोग्रामिंग और फ़ैक्टर के बारे में बहुत कुछ जानते हैं।

के functors साथ शुरू करते हैं:

struct greater { 
    bool operator()(const int& x, const int& b) const { 
    return x > y; 
} 

greater g; 
g(2,3); // returns false 
g(3,2); // returns true 

तो functors एक समारोह के रूप में आप अच्छी तरह से लागू किया जा सकता था bool ग्राम (int x, int y) नकली {वापसी x> y;} और यह उसी तरह इस्तेमाल किया।

फ़ैक्टर के बारे में अच्छी बात यह है कि आप अधिक जटिल डेटा संरचना पर काम करते समय कुछ डेटा भी स्टोर कर सकते हैं।

फिर टेम्पलेट भाग है: आप किसी भी प्रकार के लिए एक ही मज़ेदार लिखना चाहते हैं, आपको कोई परवाह नहीं है कि टाइप एक इंट, फ्लोट, कॉम्प्लेक्स ऑब्जेक्ट है, कोड वही होगा। टेम्पलेट का हिस्सा यही है।