c++ - 在编译时区分char和wchar_t

标签 c++ templates c++14

我有一个模板类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/

相关文章:

c++ - 程序在这个有效缓冲区的 delete[] 上崩溃..我认为

c++ - 未找到使用表达式模板化的静态 constexpr 成员函数

c++ - 使 LLDB 将地址重新解释为指向模板实例化类型的对象的指针

C++ 多态性/指针 - 表达式必须具有常量值

c++ - 设置一个 C 风格的数组,模板函数接受回调

c++ - 为什么二维Array中的Range for要这样写?

c++ - 在ubuntu上安装c++标准库文件

c++ - glBlendFunc() 的负色?

c++ - 重用构造函数。将右值传递给 const 左值并且不重复执行

c++11 - decltype(auto) 与 auto&& 保存 cv 限定符