yohhoyの日記

技術的メモをしていきたい日記

std::stringの地味な拡張

C++11標準ライブラリが提供する文字列std::basic_stringクラステンプレートでは、新たにpop_back, front, backメンバ関数が追加されている。(C++03以前の標準std::basic_stringでは提供されない。)

これらはシーケンスコンテナ(sequence container)の一部で提供されるオプショナルなメンバ関数であり、文字列とシーケンスコンテナとのAPI一貫性向上のために追加された。(N3337 23.2.3/p16, Table 101 Optional sequence container operations)

#include <vector>
#include <string>
#include <iostream>

template <class C>
void dump_front(const C& c)
{
  std::cout << c.front() << std::endl;
}

std::vector<int> v = /*...*/;
std::string      s = /*...*/;

// C++98/03
dump_front(v);  // OK: vector::front()が呼ばれる
dump_front(s);  // NG: 標準ではbasic_string::front提供されない

// C++11
dump_front(v);  // OK: vector::front()が呼ばれる
dump_front(s);  // OK: basic_string::front()が呼ばれる

関連URL