I'm trying to setup a structure using a std::map with std::wstring as a key and attempting to use some syntactic surgar to make key declaration/definition easy via macros and std::wstring_view (for const definition of key). Is there a way to use std::wstring_view value as std::wstring map key?
My map is defined as follows...
class Parameter
{
public:
typedef std::wstring Key;
std::variant<void*, int, bool, float, std::wstring> value_;
...
}
typedef std::map<Parameter::Key, Parameter> Parameters;
I can access the map no problem using string literals...
myParameters[L"SomeKey"] = L"SomeValue";
However if using a std::wstring_view to define a const key, gives me an error when trying to use it as a key.
static constexpr std::wstring_view SomeKeyDefined = L"SomeKey";
myParameters[SomeKeyDefined] = L"SomeValue";
Results in...
C2679: binary '[': no operator found which takes a right-hand operand of type 'const std::wstring_view' (or there is no acceptable conversion)
It's my understanding that std::wstring_view is simply a wrapper to allow me to define a const std::wstring. Is it possible to use std::wstring_view value as a map key?
Ultimately I would like to be able to have some syntactic sugar (via macros) to aid in defining some const keys. e.g.
#define PARAMETER_KEY_STRING(x) L # x
#define PARAMETER_KEY(name) static constexpr std::wstring_view name = PARAMETER_KEY_STRING(name);
Which would allow me to define const std::wstring map keys as follows
PARAMETER_KEY(SomeKey)
If this cannot be done, is there a another way to have some syntactic sugar for defining std::wstring const keys for a map?
Problem is
std::map::operator[]which accepts onlykeytype - in your casestd::wstringand the fact there is no implicit conversion fromstd::wstring_viewtostd::wstring.There are two ways to fix it:
Or IMO better:
Demo: https://godbolt.org/z/aYcGeEq5a