Re: How do you create and use an ostringstream in an initialisation list?
On Oct 12, 10:15 am, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
Adam Nielsen wrote:
[...]
#include <iostream>
#include <sstream>
struct PrintString
{
PrintString(std::string s)
{
std::cout << s << std::endl;
}
};
struct PrintNumber: public PrintString
{
PrintNumber(int iNumber)
: PrintString(
// How should this be done?
(std::ostringstream() << "The number is " << iNumber).str()
[...]
Thus, you would need to trick the compiler a little bit:
static_cast<std::ostringstream&>
(std::ostringstream() << std::dec << "The number is " << iNumber)
.str()
c) Clearly, this is way too tricky to put it into your code. You'd end up
writing a page of comments for the maintenance programmer if you did this.
On the other hand, if you wrap it into a function (a static
member function, if you prefer), it can be made readable:
class PrintNumber : public PrintString
{
private:
static std::string initBase( int i )
{
std::ostringstream s ;
s << i ;
return s.str() ;
}
public:
explicit PrintNumber( int i )
: PrintString( initBase( i ) )
{
}
} ;
I use similar functions (either in anonymous namespace, or as
static members) in initialization lists quite often.
[...]
BTW: what problem is this strange hierarchy of Print-classes supposed to
solve? It looks as though you chose a very very roundabout way to print
some numbers. Why?
I was wondering about that myself.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34