Pythonic C++

Pythonic C++

Sergey Abbakumov
std :: string s;
s = 1;

— Wow, C++, is like Python! You can assign integers to the string, — you will think, seeing that this code fragment is compiled without errors. And... You will be wrong.


It's all about the assignment statement declaration:

string& string::operator=(char ch);


which casts 1 to char.


So there is no magic. And this code will make you think why the error has crept into the code.


And if you still want this behavior like in Python, take a look at std::any https://en.cppreference.com/w/cpp/utility/any


Telegram channel: https://t.me/sea_plus_plus

Report Page