我有一个模板类simplestring,可以简单地处理TChar *及其长度。 TChar可以是char和wchar_t。
这是一个简单的左修剪方法,
simplestring<T> ltrim(const T* _s = nullptr) const
{
const T* s = _s;
if (s == nullptr)
{
#if ( sizeof(T) == 1)
s = " \t\r\n";
#else
s = L" \t\r\n";
#endif
}
constexpr int len = tstrlen(s);
find_first_not_of(s, len);
}
我希望当T为char时为s分配一个char *,否则为wchar_t *分配一个。它不会编译。 PS:我的项目支持C++ 17。
最佳答案
在C++ 17中,您可以使用 if constexpr
:
if constexpr (sizeof(T) == 1) // or (std::is_same_v<T, char>)
s = " \t\r\n";
else
s = L" \t\r\n";
关于c++ - 在编译时区分char和wchar_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693021/