Jam*_*ent 1 c++ mfc visual-studio
I'm currently working on a DLL that needs to convert back and forth between the friendly name for a value and the value itself. As this code is used in many places throughout the codebase, I want to try and keep it simple and in a single function or object so I only have to declare them once.
From my reading it looks like CMap is the tool for the job, but I can't seem to discover any combination of template arguments that compiles without errors.
My values are CString and int. I tried the following definition:
CMap<int, int, CString, CString> encodermap;
Run Code Online (Sandbox Code Playgroud)
which compiles, but when I try to add a value:
encodermap["Encoder 1"] = 0;
Run Code Online (Sandbox Code Playgroud)
I get the following compiler errors:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2501: 'encodermap' : missing storage-class or type specifiers
error C2040: 'encodermap' : 'int []' differs in levels of indirection from 'CMap<KEY,ARG_KEY,VALUE,ARG_VALUE>'
Run Code Online (Sandbox Code Playgroud)
I've tried changing the CMap to this:
CMap<CString, CString, int, int> encodermap;
Run Code Online (Sandbox Code Playgroud)
but I get the same four errors.
I'm sure I must be missing something but I'm at a loss as to what.
Because of the SDK being used for this work I'm require VS2003
The problem
I think you've inverted the key type and the valye type.
Your original declaration defines int as being the key to be searched for with operator[]. So encodermap[0] = "Encoder 1"; would work.
But when your compiler sees encodermap["Encoder 1"] = 0;, he tries to find an operator[] which takes char* (or something to which char * can be converted to) and returns an int. The last error message tells you that he couldn't find such an operator for your map.
With MSVC 2015, the error message is more concise: C2679.
The solution
你应该CMap用一个CString键和一个int值来定义你的。要知道的诀窍是,对于CStringKEY,ARG_KEY 应该是LPCWSTR. 所以正确的定义是:
CMap<CString, LPCWSTR, int, int> encodermap;
Run Code Online (Sandbox Code Playgroud)
这允许CString在地图的operator[].
现在,如果您在 Windows 上使用 MFC,您可能会使用 UNICODE 和宽字符(因此使用 LPCWSTR 而不是 LPCSTR)。调用运算符时,您必须使用 CString 或宽字面量:
encodermap[L"Encoder 1"] = 0;
encodermap[CString("Encoder 2")] = 1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6919 次 |
| 最近记录: |