利用operator實現字串與數字的通用轉換
阿新 • • 發佈:2018-12-14
利用operator來進行類型別的隱式轉換,在類中實現operator T,即可將類型別轉為T型別
template <typename T>
class string_cast
{
public:
string_cast(const std::string &from): m_from(from) {
}
operator T() const {
std::stringstream sstr(m_from);
T ret;
try {
sstr >> ret;
}
catch(std::exception & e)
{
return T(0);
}
return ret;
}
private:
const std::string &m_from;
};
string轉int的用法:
cout << string_cast<int>("12345") << endl;
string轉double的用法:
cout << string_cast<double>("12345.78") << endl;