-1

I need your help please especially to know can I convert a string Variable in an enum variable.

Here is my code:

deco_fill.h

#include <iostream>
using namespace std;
#include <string.h>

class A{

class B{
    public:
    enum tStrict{
        "ST_UNKNOWN"=-1;
        "ST_USE"=0;
        "ST_DEL"=1;
    }

    public:
    tStrict mType;

    void setStrict(tStrict& newStrict ){
        return mType=newStrict;
    }
  }
}

test.h

#include <iostream>
using namespace std;
#include <string.h>
#include <deco_fill.h>

class C
{
   public:
    A::B::tStrict CnvStrToEnum(const string& str); //This method will return   a     tStrict type

}

test.cpp

#include <iostream>
using namespace std;
#include <string.h>
#include <test.h>
#include <deco_fill.h>


A::B::tStrict C::CnvStrToEnum(const string& str)
{
   if (str=="ST_USE")
      return ST_USE;
   else if (str=="ST_DEL")
      return ST_DEL;
   else
      return ST_UNKNOWN;
 }

test_set.cpp

#include <iostream>
using namespace std;
#include <string.h>
#include <deco_fill.h>
#include <test.h>

string st=ST_USE;
A::B::tStrict strictType=CnvStrToEnum(st);


setStrict(strictType);//I want here to use the setStrict methode to set a new variable of type enum with that. This part is not important

I have a compile error in test.cpp like ST_DEL, ST_USE and ST_UNKNOWN were not declared. What's do I need here and how can I correctly the string type in my enum type. Thanks for your help.

Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
Franky N.
  • 79
  • 1
  • 9
  • I haven't written C++ in awhile, but don't you need to namespace the Enum members when you refer to them? Something like `A::B::tStrict::ST_USE`? – Carcigenicate Oct 13 '16 at 21:18
  • 1
    As far as I know, what you're trying to do is not possible, because I'm pretty sure you can't use strings as Enum identifiers. If you're trying to convert Enums to strings, there's no direct way to do it in C++, but it's already been addressed many times on this site, such as here: http://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c-and-future-c17-c20 – Random Davis Oct 13 '16 at 21:21
  • using all UPPERCASE constants in C++ is anti-pattern. – Slava Oct 13 '16 at 21:42

1 Answers1

2

enum is for numeric constants (not strings), so you can't write

enum tStrict{
    "ST_UNKNOWN"=-1; 
    "ST_USE"=0;
    "ST_DEL"=1;
}

Also note it's comma (NOT semicolon) after each enum constant.

So instead you should write:

enum tStrict{
    ST_UNKNOWN=-1,
    ST_USE,
    ST_DEL
};

Usually you can then convert enum constants to string counterparts:

    const char *tStrictStr( const enum tStrict t )
    {
        switch( t )
        {
            case ST_UNKNOWN : return "ST_UNKNOWN" ;
            case ST_USE     : return "ST_USE"     ;
            case ST_DEL     : return "ST_DEL"     ;
            default         : return "ST_UNKNOWN" ;
        }
    }
artm
  • 17,291
  • 6
  • 38
  • 54