I am well aware of techniques to convert CString
to a C-style character. One of them is to use strcpy
/_tcscpy
, and others include using CStrBuf
.
The problem:
char Destination[100];
CStringA Source; // A is for simplicity and explicit ANSI specification.
Source = "This is source string."
Now I want this:
Destination = Source;
To happen automatically. Well, that logically means writing a conversion operator in CString
class. But, as implicit as it is, I dont have privileges to change the CString
class.
I thought of writing a global conversion opertor and global assignment operator. But it doesnt work:
operator char* (const CStringA&); // Error - At least must be class-type
operator = ... // Won't work either - cannot be global.
Yes, it is definitely possible to write function (preferably a templated one). But that involves calling the function, and it is not smooth as assignment operator.
Well, I don't want to say that this is in any way recommendable, but you could hijack some lesser-used operator for a quick hack:
void operator<<=(char * dst, const std::string & s)
{
std::strcpy(dst, s.c_str());
}
int main()
{
char buf[100];
std::string s = "Hello";
buf <<= s;
}
You could even rig up a moderately safe templated version for statically sized arrays:
template <typename TChar, unsigned int N>
inline void operator<<=(TChar (&dst)[N], const std::string & s)
{
std::strncpy(dst, s.c_str(), N);
}