trim für std :: string und std :: wstring [duplizieren]

Sep 09 2020

Ich habe eine Trimmfunktion für 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);
    }

Ich möchte es sowohl für String als auch für Wstring anpassen.

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
...
}

Aber es wird nicht kompiliert. Der Befehl sizeof im Präprozessor wird nicht mit dem Fehler C1017 kompiliert

Antworten

2 vll Sep 09 2020 at 16:22

TCHARist das Vorlagenargument, kein Präprozessor-Token. Verwenden Sie if constexprstattdessen.

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");
    }
...
}