cắt cho cả std :: string và std :: wstring [trùng lặp]

Sep 09 2020

Tôi có một hàm cắt cho std :: string,

    static string trim(const string &s)
    {
        int ibegin = s.find_first_not_of(" \t\r\n");
        if (ibegin == string::npos)
        {
            return "";
        }

        int iend = s.find_last_not_of(" \t\r\n");

        return s.substr(ibegin, iend - ibegin);
    }

Tôi muốn điều chỉnh nó cho cả chuỗi và chuỗi,

template<typename TCHAR>
std::basic_string<TCHAR> trim(const std::basic_string<TCHAR>& s)
{
#if (sizeof(TCHAR)==1) 
    int ibegin = s.find_first_not_of(" \t\r\n");
#else
    int ibegin = s.find_first_not_of(L" \t\r\n");
#endif
...
}

Nhưng nó không biên dịch. sizeof trong lệnh tiền xử lý không biên dịch với lỗi C1017

Trả lời

2 vll Sep 09 2020 at 16:22

TCHARlà đối số mẫu, không phải là mã thông báo tiền xử lý. Sử dụng if constexprthay thế.

template<typename TCHAR>
std::basic_string<TCHAR> trim(const std::basic_string<TCHAR>& s)
{
    int ibegin;
    if constexpr(sizeof(TCHAR) == 1) { 
        ibegin = s.find_first_not_of(" \t\r\n");
    }
    else {
        ibegin = s.find_first_not_of(L" \t\r\n");
    }
...
}