corte para std :: string e std :: wstring [duplicar]

Sep 09 2020

Eu tenho uma função de corte para 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);
    }

Eu quero adaptá-lo para string e wstring,

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

Mas não compila. sizeof no comando do pré-processador não compila com o erro C1017

Respostas

2 vll Sep 09 2020 at 16:22

TCHARé o argumento do modelo, não um token de pré-processador. Use em seu if constexprlugar.

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