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

STLライブラリの "不等式の比較のための関数オブジェクトクラス"という定義が見つかりました。 誰かがこのコードがどのように動作してコンパイルされるか説明してください。C++の "より大きい"関数オブジェクト定義

+1

何それについて同等ですbinary_functionを定義するタイプ

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

にアクセスすることができます? 1つの使用法は、整数のコンテナを最高から最低までソートするために 'std :: sort(begin(arr)、end(arr)、std :: greater ()); – 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; 
}; 

の定義である、これはあなたが

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

'std :: result_of'とは何ですか? – 0x499602D2

+1

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

+0

私は、テンプレートのパラメータを閉じる間にスペースが必要であることを読んだので、 '> 'は'より大きくなるべきではない> '?? – 0x499602D2

0

これは、1つの型引数でインスタンス化できるテンプレートクラスです。したがって、greater<int>greater<my_class>などと言うことができます。これらのインスタンスのそれぞれは、const T&という2つの引数を取り、それを比較した結果を返すoperator()を持っています。

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

私はテンプレートプログラミングとファンクタについて知りません。

のはファンクタを見てみましょう:

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 

だからファンクタはあなたにも実装されている可能性が機能するboolグラム(int型のx、int型のy)を模擬{X> Yを返す;}そしてそれを同じように使用していました。

Functorについての素晴らしい点は、より複雑なデータ構造で作業するときに、いくつかのデータを保存できることです。

テンプレートパーツがあります。どのタイプのものでも同じファンクタを書いていますが、型がint、float、complexeオブジェクトの場合は気にしません。コードは同じになります。それはテンプレート部分のためのものです。ここ

関連する問題