दोनों std :: string और std :: wstring [डुप्लिकेट] के लिए ट्रिम करें

Sep 09 2020

मेरे पास 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);
    }

मैं इसे स्ट्रिंग और 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
...
}

लेकिन यह संकलन नहीं है। पूर्वप्रक्रमक कमांड में sizeof त्रुटि C1017 के साथ संकलित नहीं करता है

जवाब

2 vll Sep 09 2020 at 16:22

TCHARटेम्प्लेट तर्क है, प्रीप्रोसेसर टोकन नहीं है। if constexprइसके बजाय उपयोग करें ।

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