C ++ Integer Template Parameter Evaluation

This question may be very simple, but I am quite inexperienced with C ++ and am stuck while writing a simple parser. For some reason, one of the string comparison functions did not return the expected value when called. The function looks like this:

template<int length>
bool Parser::compare(const char *begin, const char *str){
   int i = 0;
   while(i != length && compareCaseInsensitive(*begin, *str)){
      i++;
      begin++;
      str++;
   }
   return i == length;
 };

      

The purpose of this function was to compare the runtime character buffer with the compile time constant vb

compare<4>(currentByte, "<!--");

      

I know there are better ways to compare a fixed-length character buffer (and used later on), but I was pretty confused when I ran this function and it always returns false even with two identical strings.

I checked with a debugger and checked the value of i at the end of the loop and it was equal to the value of the template parameter, but still the return expression was evaluated to false. Are there any special rules for working with int template parameters? I assumed the template parameter would behave like a compile-time constant.

I don't know if this is relevant, but I run the gcc g ++ compiler and debug with gdb.

If anyone could tell me what might be causing this problem it would be much appreciated.

Functions used in this code snippet:

template<typename Character>
Character toLowerCase(Character c){
    return c > 64 && c < 91 ? c | 0x10 : c;
};

template<typename Character>
bool equalsCaseInsensitive(Character a, Character b){
    return toLowerCase(a) == toLowerCase(b);
};

      

+3


source to share


1 answer


For doing case insensitive string comparisons, I would try to use the STL function std :: strcoll from a header <cstring>

that has a signature

int strcoll( const char* lhs, const char* rhs );

      

and compares two null-terminated byte strings according to the current locale. Or if you want to use your own, you can still use std :: tolower from a header <cctype>

that has a signature



int tolower( int ch );

      

and converts the specified character to lowercase according to the character conversion rules defined in the currently installed C language.

0


source







All Articles