2

Boost's lexical_cast converts numbers (or arbitrary objects) to strings and back. Should I try to use it more, say, instead of streaming things to std::stringstreams? Or is it more of a mechanism-of-last-resort?

Here's one example of two alternative approaches:

std::stringstream message;
message << "foo " << bar << ' ' << baz;
doSomething(message.str());

or

doSomething("foo " + lexical_cast<string>(bar) + " " + lexical_cast<string>(baz));

(but note my question is more general).

einpoklum
  • 118,144
  • 57
  • 340
  • 684

2 Answers2

1

Lexical cast doesn't not "mostly" convert numbers. It's a mechanisms for anything text-streamable. And yes, it depends. I freely use lexical_cast, but I don't hesitate to use std::stoi, std::to_string, Boost {Spirit|Format|Serializaton} depending on the use case.

In short: It's not a mechanism-of-last-resort. It's also not the end-all-be-all solution.


Background

  • A common objection has been that lexical_cast would be slow. This is rarely the case (anymore) since it has been specialized for common primitive types
  • The interface of lexical_cast is only appropriate when parsing should never/rarely fail; otherwise prefer an interface that reports input validation errors without exceptions
sehe
  • 374,641
  • 47
  • 450
  • 633
0

I'd say you should always use lexical_cast when converting string to a number, because without it you won't know whether it really was a number or not (bad lexical cast exception). The string stream doesn't throw anything and leaves the number uninitialized.

okaerin
  • 789
  • 5
  • 23
  • Hrm? You _can_ (and should) handle stream errors. This is a weak argument. – sehe Jul 21 '14 at 10:46
  • @einpoklum as sehe mentioned my argument isn't too strong. In your case I'd prefer the stringstream version – okaerin Jul 21 '14 at 10:53
  • I'd say the fact that `boost::lexical_cast` can only report errors via an exception is a very strong argument _against_ it. If you're dealing with user input, you don't want an exception; you want an error that you can test and handle locally. – James Kanze Jul 21 '14 at 14:23
  • @JamesKanze you can also handle the exception "somewhat" locally and besides you should always handle exceptions – okaerin Jul 21 '14 at 14:53
  • 2
    Handling exceptions should only be done at the higher levels. Handling them locally quickly leads to unreadable code; the whole point of exceptions is that you don't have to handle them locally. – James Kanze Jul 22 '14 at 09:19