我正在尝试使用
std::map
和 std::wstring
作为键来设置一个结构,并尝试使用一些语法语法通过宏和 std::wstring_view
(用于键的常量定义)使键声明/定义变得容易。有没有办法使用 std::wstring_view
值作为 std::wstring
地图键?
我的地图定义如下...
class Parameter
{
public:
typedef std::wstring Key;
std::variant<void*, int, bool, float, std::wstring> value_;
...
}
typedef std::map<Parameter::Key, Parameter> Parameters;
我可以使用字符串文字毫无问题地访问地图...
myParameters[L"SomeKey"] = L"SomeValue";
但是,如果使用
std::wstring_view
定义 const 键,则在尝试将其用作键时会出现错误。
static constexpr std::wstring_view SomeKeyDefined = L"SomeKey";
myParameters[SomeKeyDefined] = L"SomeValue";
结果...
C2679: binary '[': no operator found which takes a right-hand operand of type 'const std::wstring_view' (or there is no acceptable conversion)
我的理解是
std::wstring_view
只是一个包装器,允许我定义 const std::wstring
。是否可以使用 std::wstring_view
值作为地图键?
最终我希望能够有一些语法糖(通过宏)来帮助定义一些 const 键。例如
#define PARAMETER_KEY_STRING(x) L # x
#define PARAMETER_KEY(name) static constexpr std::wstring_view name = PARAMETER_KEY_STRING(name);
这将允许我定义 const
std::wstring
映射键如下
PARAMETER_KEY(SomeKey)
如果无法做到这一点,是否有另一种方法可以使用一些语法糖来定义映射的
std::wstring
常量键?
问题是
std::map::operator[]
只接受 key
类型 - 在你的情况下 std::wstring
并且事实上没有从 std::wstring_view
到 std::wstring
的隐式转换。
有两种解决方法:
myParameters[std::wstring{SomeKeyDefined}] = L"SomeValue";
或者我认为更好:
myParameters.emplace(SomeKeyDefined, L"SomeValue");