ตัดแต่งสำหรับทั้ง 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");
    }
...
}