-2

I have a trim function for 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);
    }

I want to adapt it for both string and 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
...
}

But it doesn't compile. sizeof in preprocessor command doesn't compile with error C1017

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 1
    I think you need some kind of `if constexpr` because the preprocessor runs before the compiler instantiates `#if` directives. – Al.G. Sep 09 '20 at 09:21

1 Answers1

2

TCHAR is the template argument, not a preprocessor token. Use if constexpr instead.

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");
    }
...
}
VLL
  • 9,634
  • 1
  • 29
  • 54