std::string::operator+(int) ?

The Partridge Family were neither partridges nor a family. Discuss.
Slidy
Posts: 80
Joined: September 9th, 2017, 1:19 pm

Re: std::string::operator+(int) ?

Post by Slidy » March 31st, 2020, 10:36 am

Something something evil macros.

Just use a function:

Code: Select all

template <typename T>
std::string tos(const T& t) { return std::to_string(t); }
or if you want to be fancy and use perfect forwarding:

Code: Select all

template <typename T>
std::string tos(T&& t) { return std::to_string(std::forward<T>(t)); }

binbinhfr
Posts: 78
Joined: May 9th, 2019, 10:57 pm

Re: std::string::operator+(int) ?

Post by binbinhfr » March 31st, 2020, 11:28 am

Hi Slidy,

thanks for your answer.
But I am curious. Can you explain what is the advantage of your solution comparing to the simple

Code: Select all

#define tos(x) std::to_string(x)
?

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: std::string::operator+(int) ?

Post by albinopapa » March 31st, 2020, 3:46 pm

Well, while there is nothing technically wrong with using macros, your usage of them can have unexpected results.

#define TOS( x ) std::to_string( x )

This should probably be: #define TOS( x ) std::to_string( ( x ) )

Probably not a big deal since you aren't using 'x' multiple times in this macro, but you can see how being lax here might have you forgetting to do so in other macros.

Macros are just a copy/paste mechanism for the compiler and no type checking by the compiler is done. You can't limit the types being sent to the TOS macro like you could using the template version Slidy posted. Granted his version doesn't limit types either, but it could be modified to do so.

By the way, if you are using some function from the standard library that begins with an underscore ( _ ), then you are probably using the wrong function, hopefully it was just a typographical error. Most functions in the standard library that begin with an underscore are reserved for internal implementations of the library and may be renamed or removed at some point.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

binbinhfr
Posts: 78
Joined: May 9th, 2019, 10:57 pm

Re: std::string::operator+(int) ?

Post by binbinhfr » March 31st, 2020, 4:22 pm

ok, I got it.

the underscore was indead a typo. ;-)

Post Reply