基数指定した文字列変換

文字列を数値に変換するところで、strtolとかstrtodとか使う訳なのですが、この関数がなんとエラーをグローバル変数で報告してくれちゃったりする。
boostとかにそれっぽいのがないかと探すと、lexical_castなるものを発見。
だけど、こいつは整数を変換するときに基数を指定できない。。

再入可能 - ryot0の日記

こんな感じかな。


<shand/radix_string.hpp>

#ifndef SHAND_RADIX_STRING_INCLUDE
#define SHAND_RADIX_STRING_INCLUDE

#include <string>
#include <sstream>
#include <bitset>
#include <iomanip>

namespace shand {

template <int Radix>
std::string to_radix_string(int x);

template <>
inline std::string to_radix_string<2>(int x)
{
    return std::bitset<8>(x).to_string();
}

template <>
inline std::string to_radix_string<8>(int x)
{
    std::ostringstream os;
    os << std::oct << x;
    return os.str();
}

template <>
inline std::string to_radix_string<10>(int x)
{
    std::ostringstream os;
    os << x;
    return os.str();
}

template <>
inline std::string to_radix_string<16>(int x)
{
    std::ostringstream os;
    os << std::hex << x;
    return os.str();
}

} // namespace shand

#endif // SHAND_RADIX_STRING_INCLUDE


サンプル

#include <iostream>
#include <string>
#include <shand/radix_string.hpp>

using namespace std;
using namespace shand;

int main()
{
    string b = to_radix_string<2>(3);   // 3を2進数の文字列に変換
    string o = to_radix_string<8>(10);  // 10を8進数の文字列に変換
    string d = to_radix_string<10>(11); // 11を10進数の文字列に変換
    string h = to_radix_string<16>(15); // 15を16進数の文字列に変換

    cout << b << endl; // 00000011
    cout << o << endl; // 12
    cout << d << endl; // 11
    cout << h << endl; // f
}

・2進数は8ビットにしかできない
・引数はintしか指定できない
・std::stringにしか変換できない


という手抜きな作りになってます・・・
関数テンプレートの部分特殊化がほしい(C++0xに入る予定はないみたい)。