1. 程式人生 > >利用operator實現字串與數字的通用轉換

利用operator實現字串與數字的通用轉換

利用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;