字符串到Enum c ++

时间:2014-11-20 20:13:48

标签: string enums

我知道这个问题已在这里得到解答:C++ string to enum  但我真的迷失了如何使用它所以请不要粗鲁;)

我想在tEnumCouleur中转换我的字符串.. 我有:

    #pragma once
    #include <map>
    #include <cassert>
    class EnumCouleur
    {
    public :

        enum tEnumCouleur{BLACK,BLUE,RED,GREEN,YELLOW,CYAN};
    std::map<std::string, tEnumCouleur> xmap = boost::assign::map_list_of<std::string, tEnumCouleur>(BLACK, "BLACK")(BLUE, "BLUE")(GREEN, "GREEN");

    //Getting an error with the "=" saying it's an unautorized initialisation 
//also getting an error at the end of std::map<std::string, tEnumCouleur> xmap = boost::assign::map_list_of<std::string, tEnumCouleur>, asking for ";" 
        // static car ce get ne sappele pas sur un objet EnumCouleur (il sera toujours le même) cout<<EnumCouleurs::c_Str(v)
        static const char * c_Str(tEnumCouleur l) {
            return strEnumCouleur[l];}
        std::map<std::string, tEnumCouleur> xmap;
    private :
        static char * strEnumCouleur[];
        //EnumCouleur();

    };

和.cpp允许我将枚举转换为字符串:

#include "EnumCouleur.h"
#include <string>

char * EnumCouleur::strEnumCouleur[] = {
    "BLACK","BLUE","RED","GREEN","YELLOW","CYAN"
};

我尝试过在链接主题上找到的两件事:

std::map<std::string, tEnumCouleur> xmap = boost::map_list_of("A", A)("B", B)("C",C);

struct responseHeaderMap : public std::map<std::string, tEnumCouleur>
{
    responseHeaderMap()
    {
        this->operator[]("BLACK") =  BLACK;
        this->operator[]("BLUE") = BLUE;
        this->operator[]("RED") = RED;
        this->operator[]("GREEN") =  GREEN;
        this->operator[]("YELLOW") = YELLOW;
        this->operator[]("CYAN") = CYAN;
    };
    ~responseHeaderMap(){}
};

我真的不知道如何使用它..让我们说我的程序从文本文档中获取了一个字符串。我确定这个字符串是正确的。我想做一个tEnumCouleur,以适应一个构造函数:

Segment( const Point p1, const Point p2, EnumCouleur::tEnumCouleur v);

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您实际需要做的是翻转std::map左右,以便将字符串映射到enum而不是enum到字符串。然后,您可以执行xmap[string]并获取enum

所以你可以做到

std::map<std::string, tEnumCouleur> xmap = boost::assign::map_list_of<std::string, tEnumCouleur>(A, "A")(B, "B")(C, "C");

然后你可以简单地执行xmap["BLACK"]并获得枚举值BLACK