rrajanuk
rrajanuk

Reputation: 27

Enum Class does not accept text with hyphen/dash in C++

I am creating an enum class but the CDT compiler in Eclipse is throwing error because my constant list has hyphens. I cannot avoid the hyphen/dash because it is part of the product codes. Is there a workaround?

enum class ProductCode{
   JELLY-BEANS,
   SALE,
   TWISTED-TWIRLS,
   5-STARS
}

Upvotes: 0

Views: 1159

Answers (3)

Jan Schultke
Jan Schultke

Reputation: 39668

A hyphen (-) can not be part of identifiers in the C++ language.

An identifier is an arbitrarily long sequence of digits, underscores, lowercase and uppercase Latin letters, and most Unicode characters. It must begin with an underscore or letter. Also see cppreference/Identifiers.

Typically, the underscore (_) character is used in identifiers like macros and enum constants instead:

enum class ProductCode {
   JELLY_BEANS,
   SALE,
   TWISTED_TWIRLS,
   FIVE_STARS // this also can't start with '5'
}

Enum constants don't store text, so they don't need to be exactly formatted like your product codes anyways. To convert from enum constants to your product codes, you could do the following:

#include <map>

constexpr const char* textOf(ProductCode code) {
    switch (code) {
        case ProductCode::JELLY_BEANS: return "JELLY-BEANS";
        case ProductCode::SALE: return "SALE";
        case ProductCode::TWISTED_TWIRLS: return "TWISTED-TWIRLS";
        case ProductCode::FIVE_STARS: return "5-STARS";
    }
}

ProductCode codeOf(const std::string &str) {
    static const std::map<std::string, ProductCode> map{
        {textOf(ProductCode::JELLY_BEANS), ProductCode::JELLY_BEANS},
        {textOf(ProductCode::SALE), ProductCode::SALE},
        {textOf(ProductCode::TWISTED_TWIRLS), ProductCode::TWISTED_TWIRLS},
        {textOf(ProductCode::FIVE_STARS), ProductCode::FIVE_STARS}
    };
    return map.at(str);
}

Upvotes: 3

francis duvivier
francis duvivier

Reputation: 2186

As stated[1,2], this cannot be done with an enum because then your constants need to be valid C++ identifiers and a hyphen or starting with a number would make it invalid.

However, as a "workaround", you can use a C++ map instead like this:

#include <iostream>
#include <map>

std::map < std::string, int >
  ProductCode = {
  {"JELLY-BEANS", 0},
  {"SALE", 1},
  {"TWISTED-TWIRLS", 2},
  {"5-STARS", 3}
};

int main ()
{
  std::cout << "ProductCode[\"TWISTED-TWIRLS\"] is " << ProductCode["TWISTED-TWIRLS"];
  return 0;
}

Testable here: https://onlinegdb.com/SJ3K9B5mw

Upvotes: 0

tdao
tdao

Reputation: 17668

I cannot avoid the hyphen/dash because it is part of the Product Codes, is there a work around.

You can't use hyphen - in any of the variables or constants names in C++.

There is no workaround, except you may use underscore '_' instead.

Upvotes: 1

Related Questions