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

Znalazłem definicję "klasy obiektu funkcji dla porównania większego niż nierówności" w bibliotece STL. Czy ktoś może mi wyjaśnić, w jaki sposób działa i kompiluje ten kod?C++ "większa" definicja obiektu funkcji

+1

Co o nim ? Jednym z zastosowań może być 'std :: sort (begin (arr), end (arr), std :: greater ());' do sortowania kontenerów liczb całkowitych od najwyższego do najniższego. – chris

Odpowiedz

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

tutaj jest definicja 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; 
}; 

ten pozwala uzyskać dostęp do typów Definiowanie binary_function

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

co jest równoważne

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

Co to jest 'std :: result_of'? – 0x499602D2

+1

@ David, http://en.cppreference.com/w/cpp/types/result_of – chris

+0

Przeczytałem, że powinien istnieć odstęp między zamykającymi się parametrami szablonu ... Tak więc nie powinno być 'większe> '?? – 0x499602D2

0

Jest to klasa szablonów, które można utworzyć z jednym argumentem typu. Możesz więc powiedzieć: greater<int>, greater<my_class> itd. Każda z tych instancji ma operatora(), który pobiera dwa argumenty typu const T& i zwraca wynik ich porównania.

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

Nie wiem, czy wiesz wiele o programowaniu szablonów i funktorach.

Zacznijmy funktorów:

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 

Więc funktory drwić funkcję mogłeś równie dobrze realizowane bool g (int x, int y) {return x> y;} i wykorzystał je w ten sam sposób.

Fajną cechą funktorów jest to, że można również przechowywać pewne dane podczas pracy nad bardziej złożoną strukturą danych.

Następnie jest część szablonu: chcesz napisać ten sam funktor dla dowolnego typu, nie obchodzi cię, czy typ to int, float, complexe object, kod będzie taki sam. Po to jest część szablonu.

Powiązane problemy