Conversion to int with static_cast in c ++

1

Doing a search found something related to this error. I have the following error below:

  

ERROR: date.cxx: In member function 'int   CurrentDateTime :: GetMonth (const string &) ': date.cxx: 125: 18: error:   can not convert 'const Month' to 'int' in return

related to:

int CurrentDateTime::GetMonth(const std::string& input)
{
    for(const auto& itr : monthinfo) 
    {
      if(itr.first == input)
      return static_cast<std::vector<int>itr.second>;
    }
}

where montinfo comes from:

enum class Month
{
  Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
};

// Datastructure for string to num conversion in month(.i.e."Mar" Month to 3)
std::array<std::pair<std::string, Month>, 12> monthinfo = 
{
    std::make_pair(std::string("Jan"), Month::Jan),
    std::make_pair(std::string("Feb"), Month::Feb),
    std::make_pair(std::string("Mar"), Month::Mar),
    std::make_pair(std::string("Apr"), Month::Apr),
    std::make_pair(std::string("May"), Month::May),
    std::make_pair(std::string("Jun"), Month::Jun),
    std::make_pair(std::string("Jul"), Month::Jul),
    std::make_pair(std::string("Aug"), Month::Aug),
    std::make_pair(std::string("Sep"), Month::Sep),
    std::make_pair(std::string("Oct"), Month::Oct),
    std::make_pair(std::string("Nov"), Month::Nov),
    std::make_pair(std::string("Dec"), Month::Dec)
};

I read that enum class does not implicitly convert to int because of being purposeful, you had to use a static_cast in itr.second .

I tried to do something like this would it really be?

int CurrentDateTime::GetMonth(const std::string& input)
{
    for(const auto& itr : monthinfo) 
    {
      if(itr.first == input)
      return static_cast<std::vector<int>itr.second>;
    }
}
    
asked by anonymous 13.09.2017 / 20:09

1 answer

1

Well, by responding directly to your question, the correct way to use static_cast , in this case, is to replace:

return static_cast<std::vector<int>itr.second>;

by:

return static_cast<int>(itr.second);

Because you are converting an item from enum class Month to an integer.

Now, honestly, I do not think it makes sense to do that. enum class was created exactly to avoid these unwanted conversions. The correct thing is that in the function GetMonth it returns a enum class Month . Or in other words, it has the following signature:

Month GetMonth(const std::string&) const;

Now, if you really want a conversion to integer, use enum default (without class )

    
14.09.2017 / 00:32