2012-07-12 44 views
1

不幸的是,在我目前的項目中我不能使用boost,所以我試圖模仿boost::lexical_cast(減去大多數錯誤檢查boost的行爲)的行爲。我有以下功能,哪些工作。模仿boost lexical_cast操作

// Convert a string to a primitive, works 
// (Shamelessly taken from another stack overflow post) 
template <typename T> 
T string_utility::lexical_cast(const string &in) 
{ 
    stringstream out(in); 

    T result; 
    if ((out >> result).fail() || !(out >> std::ws).eof()) 
    { 
     throw std::bad_cast(); 
    } 

    return result; 
} 

// Convert a primitive to a string 
// Works, not quite the syntax I want 
template <typename T> 
string string_utility::lexical_cast(const T in) 
{ 
    stringstream out; 
    out << in; 

    string result; 
    if ((out >> result).fail()) 
    { 
     throw std::bad_cast(); 
    } 

    return result; 
} 

我一直希望能夠使用相同的語法來保持一致性,但我無法弄清楚。

將字符串轉換爲原語很好。

int i = lexical_cast<int>("123");

的otherway,但是,看起來像這樣:

string foo = lexical_cast(123); 

// What I want 
// string foo = lexical_cast<string>(123); 

編輯:感謝ecatmur 我不得不四處切換模板參數,但下面不正是我想要的東西。

template<typename Out, typename In> Out lexical_cast(In input) 
{ 
    stringstream ss; 
    ss << input; 

    Out r; 
    if ((ss >> r).fail() || !(ss >> std::ws).eof()) 
    { 
     throw std::bad_cast(); 
    } 

    return r; 
} 
+1

爲什麼不剪切和粘貼boost庫中的代碼? – Nick 2012-07-12 15:26:17

回答

4

基本模板代碼lexical_cast是:

template<typename In, typename Out> Out lexical_cast(In in) { 
    stringstream ss; 
    ss << in; 
    if (ss.fail()) throw bad_cast(); 
    ss >> out; 
    return out; 
} 

添加錯誤檢查和專長爲(在==串)等任意的。

相關問題