< VC++ .NET と、メンバ関数テンプレート | お手軽矩形塗りつぶし >

April 4, 2005

std::list の operator ==

std::list には、 operator == が実装されているので、以下のようにリストが等しいかを比較することができる。
#include <list>

int main(
    int     argc,
    char**  argv )
{
    std::list<Foo>  FooList1;
    std::list<Foo>  FooList2;
    
    if ( FooList1 == FooList2 )
        std::cout << "FooList1 == FooList2" << endl;
    else
        std::cout << "FooList1 != FooList2" << endl;
    
    return 0;
}
上のソースで Foo が、組み込み型の typedef だったりすると、上のソースはコンパイルできるが、ユーザ定義型の場合はコンパイルエラーとなる。 VC++ .NET だとこんな感じ。
c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\xutility(1078) : error C2678: 二項演算子 '==' : 型 'const std::allocator<_Ty>::value_type' の左オペランドを扱う演算子が見つかりません (または変換できません) (新しい動作; ヘルプを参照)。
        with
        [
            _Ty=Foo
        ]
        c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\xutility(1100) : コンパイルされたクラスのテンプレートのインスタンス化 'std::pair<_Ty1,_Ty2> std::mismatch<_InIt1,_InIt2>(_InIt1,_InIt1,_InIt2)' の参照を確認してください
        with
        [
            _Ty1=std::list<Foo>::const_iterator,
            _Ty2=std::list<Foo>::const_iterator,
            _InIt1=std::list<Foo>::const_iterator,
            _InIt2=std::list<Foo>::const_iterator
        ]
        c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\list(980) : コンパイルされたクラスのテンプレートのインスタンス化 'bool std::equal<std::list<_Ty>::const_iterator,std::list<_Ty>::const_iterator>(_InIt1,_InIt1,_InIt2)' の参照を確認してください
        with
        [
            _Ty=Foo,
            _InIt1=std::list<Foo>::const_iterator,
            _InIt2=std::list<Foo>::const_iterator
        ]
        c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\list(987) : コンパイルされたクラスのテンプレートのインスタンス化 'bool std::operator ==<Foo,std::allocator<_Ty>>(const std::list<_Ty> &,const std::list<_Ty> &)' の参照を確認してください
        with
        [
            _Ty=Foo
        ]
        c:\work\LayOutManagerStep2\LayOutManager\LayOutView.cpp(1548) : コンパイルされたクラスのテンプレートのインスタンス化 'bool std::operator !=<Foo,std::allocator<_Ty>>(const std::list<_Ty> &,const std::list<_Ty> &)' の参照を確認してください
        with
        [
            _Ty=Foo
        ]
ようは、Foo を比較するための operator == が定義されている必要があるんだな、と思った私は以下のようなインターフェースで定義してみた。
// これだとコンパイルエラー
inline bool operator == (
    Foo& lhs, 
    Foo& rhs )
{
    // 二つの値が等しいかどうかを返すコードは省略
}

inline bool operator != ( 
    Foo&    lhs, 
    Foo&    rhs )
{
    return !( lhs == rhs );
}
コンパイル・・・結果は同じエラー。しばらくエラーの内容を見つめていたが、よく見るとちゃんと書いてある。正解はこう。
inline bool operator == ( 
    const Foo&  lhs, 
    const Foo&  rhs )
{
    // 二つの値が等しいかどうかを返すコードは省略
}

inline bool operator != ( 
    const Foo&  lhs, 
    const Foo&  rhs )
{
    return !( lhs == rhs );
}

トラックバック

このエントリーにトラックバック:
http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/914

コメント

コメントする

※ コメントスパム対策のため、コメント本文はおはよう、こんにちわ、こんばんわのいずれかより始めるようにしてください。

name:
email:

※ 必要ですが、表示しません。

url:
情報を保存する ?