简体   繁体   English

在不区分大小写的 std::map 中无法将 std::wstring 转换为 LPCTSTR

[英]Can't convert std::wstring to LPCTSTR in case-insensitive std::map

I'm trying to implement a case-insensitive version of std::map .我正在尝试实现std::map的不区分大小写版本。 Here's what I have so far.这是我到目前为止所拥有的。

struct NOCASECOMPARE_STRUCT
{
    bool operator() (LPCTSTR psz1, LPCTSTR psz2) const
    {
        return _tcsicmp(psz1, psz2) < 0;
    }
};

std::map<std::wstring, int, NOCASECOMPARE_STRUCT> m_IndexLookup;

IColumn* operator[](LPCTSTR pszColumn) const
{
    auto it = m_IndexLookup.find((LPTSTR)pszColumn);
    if (it != m_IndexLookup.end())
        return m_pColumns[it->second];
    ASSERT(FALSE);
    return nullptr;
}

The code above produces compile errors.上面的代码会产生编译错误。 While the hundreds of lines of STL compile errors are virtually impossible to read, Visual Studio does select a more meaningful message to put in the error list.虽然 STL 的数百行编译错误几乎无法阅读,但 Visual Studio 确实为 select 提供了一条更有意义的消息以放入错误列表中。

'bool NOCASECOMPARE_STRUCT::operator ()(LPCTSTR,LPCTSTR) const': cannot convert argument 1 from 'const _Kty' to 'LPCTSTR' 'bool NOCASECOMPARE_STRUCT::operator ()(LPCTSTR,LPCTSTR) const':无法将参数 1 从 'const _Kty' 转换为 'LPCTSTR'
with
[ [
_Kty=std::wstring _Kty=std::wstring
] ]

If I change the compare method's signature to accept std::wstring arguments, that fixes the problem but then argument 2 can't be converted.如果我将比较方法的签名更改为接受std::wstring arguments,则可以解决问题,但无法转换参数 2。 I suppose I can change the signature to one of each but was hoping to make my code more general purpose.我想我可以将签名更改为每个签名,但希望使我的代码更通用。

Questions:问题:

  1. Why can't a std::wstring convert to LPCTSTR (I'm using a Unicode build)?为什么std::wstring不能转换为LPCTSTR (我使用的是 Unicode 构建)?

  2. Is there a workaround without changing my compare method signature?有没有不改变我的比较方法签名的解决方法?

Your comparison operator should take two const std::wstring objects as input because that is what std::map will pass to it.您的比较运算符应该将两个const std::wstring对象作为输入,因为这是std::map将传递给它的。 From that, use the c_str() method and do your comparison:从那里,使用c_str()方法并进行比较:

struct NOCASECOMPARE_STRUCT
{
    bool operator() (const std::wstring& sz1, const std::wstring& sz2) const
    {
        const wchar* psz1 = sz1.c_str();
        const wchar* psz2 = sz2.c_str();
        return _tcsicmp(psz1, psz2) < 0;
    }
};

You could resort to one liners, but doing it this way is easier for debugging.您可以使用一个衬里,但这样做更容易调试。

When searching, pass the argument as a wstring :搜索时,将参数作为wstring传递:

IColumn* operator[](LPCTSTR pszColumn) const
{
    auto it = m_IndexLookup.find(std::wstring(pszColumn));
    ...

LPCTSTR is basically const whar* . LPCTSTR基本上是const whar* You can't convert a std::wstring to a const wchar* directly, but you can via c_str() .您不能直接将std::wstring转换为const wchar* ,但可以通过c_str()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM