0

Is it possible to overload conversion operator from int to std::string? Is it possible to use this function:

void printToLog(std::string text);

Like this:

int a = 5;
printToLog(a);

Or this:

int a = 5;
printToLog(a + " bombs have been planted.");

?

0

1 Answer 1

0

There's a function for it in the standard library. The aptly named std::to_string:

int a = 5;
printToLog(std::to_string(a) + " bombs have been planted.");

You cannot add a conversion operator for this purpose. Such an operator can only be a member of a class type, and int is not a class type. Neither can you add a converting constructor to std::string. Use the mechanism the standard gives you.

Sign up to request clarification or add additional context in comments.

4 Comments

I know, but I'm asking: Is it possible to make conversion operator from int to std::string?
@lollypap54 - No. And why would one do that? To avoid some typing? It's a bad reason.
Well yeah, it's pretty bad for this exact purpose, but sometimes you just want to know: is it possible? :/
@lollypap54 - Like I already said. No.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.