我如何在静态库 (.lib) 中同时支持 Unicode 和多字节字符集?

How can i suppport both Unicode and Multi-Byte Character Set in Static library (.lib)?

我正在使用 visual studio 2015,我想编写可在 Unicode 项目和多字节项目中使用的 C++ 静态库,我该怎么做?

例如我有这个代码:

namespace Reg
{
    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCTSTR lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyEx(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }
}

您可以按照通常用于 Win32 函数的方式进行操作:

CreateKeyW(..)  { unicode implementation }
CreateKeyA(..) { byte string implementation }
#ifdef UNICODE
#define CreateKey CreateKeyW
#else
#define CreateKey CreateKeyA
#endif

就像 Raymond Chen 在评论中建议的那样,您可以使用两个单独的重载函数 - 一个用于 Ansi,一个用于 Unicode:

namespace Reg
{
    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCSTR  lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyExA(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }

    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCWSTR lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyExW(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }
}

或者,就像 rubenvb 所建议的那样,完全忘记 Ansi 函数,只关注 Unicode 本身:

namespace Reg
{
    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCWSTR lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyExW(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }
}