sadegh wrote:
On Apr 9, 10:39 am, Gianni Mariani <gi3nos...@mariani.wswrote:
>>sadegh wrote:
>>>So what shoud I do to convert any type to const char*?
Does the caller expect to have to delete the memory on the returned string ?
I dont know. but for example I want to call the toCStr() function like
these:
AfxMessageBox(toCStr(8)); // showing the number "8"
or
m_EditBox.SetWindowText(toCStr(8)); // insert the number "8" into an
edit box
What you want is an object that extends the life of the string until the
function call returns. The catch with this is that the lifetime of the
string is very short, although longer than a dead return value. Once
the expression is evaluated, the memory of the string is no longer
valid. Hence, don't be caught holding on to a pointer from the toCStr
below otherwise you will run into nasty probs.
// toCStr header
#include <sstream>
#include <string>
template <typename T>
std::string ToString( const T & val )
{
std::ostringstream l_out;
l_out << val;
return l_out.str();
}
struct toCStr
{
const std::string m_value;
template <typename T>
toCStr( const T & ival )
: m_value( ToString( ival ) )
{
}
operator const char * () const
{
return m_value.c_str();
}
};
/// example code
#include <iostream>
void foo( const char * str )
{
std::cout << str << "\n";
}
int main()
{
foo( toCStr( 8 ) );
}