2012/02/23

Very very small tips on STL std::pair

STL std::pair< >についての小ネタ

ちょっと備忘録的なものですが、std::pairって 下記のように算術演算子が overloadされているんですね。知らなかった。

#include <utility>
class TestClass
{
    // ... some implementation here
};

TestClass test1, test2;

std::pair<TestClass, int> obj1(test1, 2), obj2(test2, 3);

bool ret = (obj1 == obj2);  // TestClassに bool operator==(const TestClass& rhs) const などが定義されていれば可能

ret = (obj1 < obj2);  // TestClassに bool operator<(const TestClass& rhs) constなどが定義されていれば可能


テンプレートのインスタンス化は利用される時まで遅らせるという仕組みがうまく利用されている実装ですね。




This is very very small tips in terms of std::pair< > .

I didn't know that std::pair< > implementation also overloads arithmetic operators until now.

#include <utility>
class TestClass
{
    // ... some implementation here
};

TestClass test1, test2;

std::pair<TestClass, int> obj1(test1, 2), obj2(test2, 3);

bool ret = (obj1 == obj2);  // possible if TestClass define e.g. bool operator==(const TestClass& rhs) const

ret = (obj1 < obj2);  // possible if TestClass defines e.g. bool operator<(const TestClass& rhs) const


Now we can see that lazy evaluation of the template instantiation surely makes for.



Reference: C++ Reference - pair

0 件のコメント:

コメントを投稿