Reputation: 811
In VS2008, I try to construct a CString from a char, as follows:
CString str = CString(_T('A') + 5);
But will get the following compile error:
error C2440: '' : cannot convert from 'int' to 'CString'
I belive TCHAR and int is exchangable in C++, so why it refuses to accept the TCHAR type parameter to construct a CString?
The purpose of the line is to construct a CString with only one character _T('F'). Not to get "A5".
I try to understand how the compiler processes the code, as follows:
It will first promote _T('A') to an integer.
It will add the integer value of _T('A') by 5.
It will get a new integer and cannot find a way to convert it back to TCHAR, which can be used as input parameter for CString constructor.
Upvotes: 0
Views: 346
Reputation: 8598
The CstringT
constructors that accept a char
or a wchar_t
are explicit
. See the docs.
The explicit
specifier in C++ means that the compiler is not allowed to do an implicit conversion of the parameter(s). See also explicit specifier.
Thus the compiler cannot (is not allowed to) implicitly convert the int
value to char
or wchar_t
.
(Note that this depends on the flag _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
being set. Without the flag being set, the constructors are not explicit, but then it's ambiguous which constructor to chose.)
So you need to explicitly cast the parameter to char
or wchar_t
, depending on what you want:
CStringA str = CStringA(static_cast<char>('A' + 5));
or:
CStringW str = CStringW(static_cast<wchar_t>(L'A' + 5));
Upvotes: 1
Reputation: 5166
CString will not implicitly convert an int to CString. However you can try like so
CString str;
char c = 'A';
int i = 5;
str.Format(L"%c%d",c, i); // unicode assumed
Upvotes: 1