Extension Member Function

comp.std.c++ - Extension methods c++0x


C#の拡張メソッドいいなー、C++0xでもできたらいいのになー」という話


今はこんな感じでしか書けないけど

string str = "     hello , world     !!!";
to_upper(split(trim_left(str), '<')[0]));

こんな感じで書きたいよね、と

string str = "     hello , world     !!!";
str.trim_left().split('<')[0].to_upper();


私も最近そう思います
(C#では拡張メソッド使えばstr.IsNullOrEmpty()とか書けるからねー)



いまのC++だとこんなふうにするしかないかなー

#include <string>

namespace shand { namespace extension {

class string : public std::string {
public:
    string(const std::string& other)
        : std::string(other) {}

    string& trim_right()
    {
        erase(find_last_not_of(' ')+1);
        return *this;
    }
};

}} // namespace shand::extension

int main()
{
    using shand::extension::string;

    string str = "Hello World   ";
    str.trim_right();

    return 0;
}

std::basic_stringは仮想関数テーブル持ってないから良くはないんだけど