For Programmers: Free Programming Magazines  


Home > Archive > Visual Studio > January 2006 > Strange behavoiur of ostringstream (VS.NET 2003 and C++ at all)









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Strange behavoiur of ostringstream (VS.NET 2003 and C++ at all)
Wladimir Mutel

2006-01-26, 7:03 pm

Hi,

Here is my sample. It is very simple console Win32 C++ project
but same behaviour is reproducible in other contexts.
---- stdafx.h :
#pragma once

#include <iostream>
#include <tchar.h>

---- sformat.cpp :
#include "stdafx.h"
#include <sstream>

#define SFORMAT(e) ((dynamic_cast<const
std::ostringstream&>(std::ostringstream() << e)).str())
// you have to turn on /GR (rtti) for dynamic_cast.

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << SFORMAT("2 x " << " 2 = " << 2*2);
return 0;
}
----
The strangeness is that first string constant ("2 x ")
is output by method

_Myt& basic_ostream<_Elem, _Traits>::operator<<(const void *_Val)
(header "ostream", line 414),

and the second one (" 2 = ") -
by out-of-class template inserter function

basic_ostream<_Elem, _Traits>& operator<<(basic_ostream<_Elem, _Traits>&
_Ostr, const char *_Val)
(header "ostream", line 612)

Anybody knows why C++ compiler decides to lookup operators << in such
way, and how to work around this problem ? Btw, I just have reproduced
the same behaviour under Linux/g++ 3.3.5 as well as 4.0.2, with minimal
changes to the source (_TCHAR->char, _tmain -> main, and removed
stdafx.h).

Something strange is happening in C++ world.

Thank you in advance for your replies.

Wladimir Mutel

2006-01-27, 7:59 am


Okay, I managed to fix the problem by taking reference from this
newly-created object :
template <class C> inline C& identity(C& c) {return c;}

#define SFORMAT(e) ((dynamic_cast<const
std::ostringstream&>(identity(std::ostringstream()) << e)).str())

But anyway, it is difficult for me to understand why should I jump from
such hoops ?
Why the compiler could not upcast it to reference itself ?
Why there are different lookups for T and T& ?

I would appreciate if you share your thoughts on this issue .

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com