c++visual-c++mfcvisual-c++-6visual-c++-2005

Error with CString when I import into VC++2005?


I wrote code in VC++6.0 and imported it into VC++2005. I get an ambiguous error with the unicode insertion now?

CString s;

s.Format("%f\r\n", (double)timebTime.time + (double)timebTime.millitm / 1000);
s+="RAMP,"; 
s+=0x00b5;  // <-- Error: VC++(2005):  "error C2593: 'operator +=' is ambiguous"
s+="m";

Solution

  • Note that VC++6.0's default compilation model is ANSI/MBCS (i.e. TCHAR is a char, CString is a sequence of char's, etc.), instead VC++2005's default compilation model is Unicode (i.e. TCHAR is wchar_t, CString is actually a CStringW, i.e. a wchar_t string).

    I'd just use the Unicode model (don't bother with ANSI/MBCS compatibility and TCHAR, _T("..."), etc.), and adjust your code like this:

    static const wchar_t microSign = 0x00B5;
    
    CString s;  
    s.Format(L"%f\r\n", 
        static_cast<double>(timebTime.time) +
        static_cast<double>(timebTime.millitm) / 1000.0);
    s += L"RAMP,"; 
    s += microSign;
    s += L"m";
    

    Note that the use of a named constant (like microSign) makes the code more readable than a "magic number" like 0x00B5.

    Moreover, I'd store the format string (including the "RAMP,µm" part) in the app resources and load it from there instead of building it in the source code.