确定wchar_t是内置类型还是别名



是的,wchar_t应该是c++中的内置类型;不幸的是,对于一些(非常)老的编译器,情况并非如此。😟

是否有一种(特定于编译器的,例如GCC/g++)方法来确定wchar_t是内置类型(关键字)还是typedef?其原因是判断f(wchar_t)是否可以过载;如果wchar_ttypedef,它将(很可能)与f(uint16_t)f(uint32_t)相同。

Microsoft Visual c++有_NATIVE_WCHAR_T_DEFINED,所以我可以写:

#include <stdint.h>
#if defined(_MSC_VER)
#define MY_PROJECT_wchar_t_is_built_in_ (_NATIVE_WCHAR_T_DEFINED == 1)
#else
#define MY_PROJECT_wchar_t_is_built_in_ 1
#endif
void f(uint16_t ch_utf16) { /* UTF-16 processing */ }
void f(uint32_t ch_utf32) { /* UTF-32 processing */ }
#if MY_PROJECT_wchar_t_is_built_in_
#include <type_traits>
void f(whcar_t ch_)
{
using wchar_t_type = std::conditional<sizeof(wchar_t) == sizeof(uint32_t), uint32_t, uint16_t>::type;
#ifdef _WIN32
static_assert(sizeof(wchar_t_type) == sizeof(uint16_t), "wchar_t should be 16-bits on Windows.");
#endif
const auto ch = reinterpret_cast<wchar_t_type>(ch_);
f(ch);
}
#endif

扩展TMP可能不会工作(例如,std::enable_if)…因为这是一个旧的编译器首先引起的问题!

Ayxan Haqverdili在评论中使用templatesizeof()的建议解决了我的问题。(这也说明了为什么"为什么?"是必要的。)

我的代码现在是:

void f_(uint16_t ch_utf16) { /* UTF-16 processing */ }
void f_(uint32_t ch_utf32) { /* UTF-32 processing */ }
template<typename T>
void f(T ch_)
{
static_assert(sizeof(T) == sizeof(wchar_t), "T should be wchar_t");
if (sizeof(T) == sizeof(uint16_t))
{
const auto ch = reinterpret_cast<uint16_t>(ch_);
f_(ch);
}
else if (sizeof(T) == sizeof(uint32_t))
{
const auto ch = reinterpret_cast<uint32_t>(ch_);
f_(ch);
}
else
{
throw ...;
}
}

最新更新