hem std :: string hem de std :: wstring için trim [duplicate]

Sep 09 2020

Std :: string için bir trim fonksiyonum var,

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

Bunu hem string hem de wstring için uyarlamak istiyorum,

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

Ama derlemez. önişlemci komutundaki sizeof, C1017 hatasıyla derlenmiyor

Yanıtlar

2 vll Sep 09 2020 at 16:22

TCHARşablon argümanıdır, önişlemci simgesi değildir. if constexprBunun yerine kullanın .

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