lundi 25 novembre 2013

Override a default STL operator >>

In that question, user need to override the default STL operator >> for complex number. First keep in mind that the STL provide a template for complex number define in <complex> and that this type come with its own syntax for I/O.

By default the syntax is (real,imag).

As the user want to use: real+imagi, we have to change the default behavior.

In the following you will see how I wrote a new global function to override the default operator and how I use a Regular Expression to extract the real and imaginary number.

template<class _Ty> inline istream& operator>>(istream& _Istr, complex<_Ty>& _Right)
{
// extract a complex<_Ty> with syntax REAL+IMAGi
long double _Real = 0;
long double _Imag = 0;
string s; _Istr >> s;
string regexPattern = string(R"r(([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)\s*\+\s*([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)i)r");
regex reg(regexPattern);
smatch sm; // same as std::match_results<const char*> cm;
regex_match (s,sm,reg);

_Real = std::atof(sm[1].str().c_str());
_Imag = std::atof(sm[2].str().c_str());

_Right = std::complex<_Ty>((_Ty)(_Real), (_Ty)(_Imag));

return (_Istr);
}


There is place for improvement in that version:


  • no match

  • match are not number

  • etc…

But it’s a good example of how to start!

Aucun commentaire :

Enregistrer un commentaire