trim pour std :: string et std :: wstring [duplicate]
Sep 09 2020
J'ai une fonction trim pour 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);
}
Je veux l'adapter à la fois pour string et 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
...
}
Mais il ne compile pas. sizeof dans la commande du préprocesseur ne se compile pas avec l'erreur C1017
Réponses
2 vll Sep 09 2020 at 16:22
TCHARest l'argument du modèle, pas un jeton de préprocesseur. Utilisez if constexprplutôt.
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");
}
...
}