lundi 2 novembre 2015

Why is std::underlying_type

Consider this trivial code:

int main() {
  enum Simple { one = 1, two = 2 };
  Simple m1 = static_cast<Simple>(-1);
  if (m1 < 0) return -1;
  return 1;
}

Not surprisingly, this returns -1.

What is surprising, is that when I used std::underlying_type<Simple>, the underlying type is "unsigned int". wtf? If the underlying type of Simple is unsigned, how did it get to be less than zero?

Further evidence:

int main(int argc, char *argv[]) {
  enum Simple { one = 1, two = 2 };
  Simple m1 = static_cast<Simple>(-1);

  // This doesn't even compile "no viable conversion"
  std::underlying_type<Simple>::type underlying = m1;

  long long llm1 = m1;

  std::cout << "simple=" << m1
            << " underlying=" << underlying
            << " long long=" << llm1
            << "\n";
}

Produces:

simple=-1 underlying=4294967295 long long=4294967295

Aucun commentaire:

Enregistrer un commentaire