检查枚举成员是否已定义?

时间:2015-11-05 21:11:44

标签: c++ enums

我在命名空间中定义了很长的枚举成员列表:

namespace nsexp{
  enum expname{
    AMS1,
    AMS2,
    BESS1,
    BESS2,
    ...
    };
}

对我来说,不时评论其中的一些非常有用,例如:

namespace nsexp{
  enum expname{
    AMS1,
    AMS2,
    BESS1,
    //BESS2,
    ...
    };
}

这样我就可以将它们从我的程序中排除。但是,这会在发生这种情况的函数中产生一些冲突:

strcpy(filename[nsexp::BESS2],"bess/data_exp2");

我也可以解决此行的评论,但如果我排除了许多成员,这可能会很累人。有没有办法检查成员是否存在于命名空间中?

我正在寻找类似的东西:

if("BESS2 exists") strcpy(filename[nsexp::BESS2],"bess/data_exp2");

3 个答案:

答案 0 :(得分:2)

构建一个简单的检查器对象,它允许您在运行时查询禁用标志的状态。

trunc(<<date>>, 'MM')

预期产出:

#include <iostream>

#define RUNTIME_CHECKS 1

namespace nsexp{
    enum expname{
        AMS1,
        AMS2,
        BESS1,
        BESS2,
//        ...
        NOF_EXPNAME
    };


    class checker
    {
#if RUNTIME_CHECKS
        struct impl
        {
            impl() {
                std::fill(std::begin(disabled), std::end(disabled), false);
            }
            bool disabled[NOF_EXPNAME];
        };

        static impl& statics() {
            static impl _;
            return _;
        }

    public:

        static void disable(expname e) {
            statics().disabled[e] = true;
        }

        static bool disabled(expname e)
        {
            return statics().disabled[e];
        }
#else
    public:
        static void disable(expname e) {
            // nop - optimised away
        }

        static bool disabled(expname e)
        {
            // will be optimised away
            return false;
        }
#endif
    };
}

using namespace std;

auto main() -> int
{
    nsexp::checker::disable(nsexp::AMS2);
    nsexp::checker::disable(nsexp::BESS2);

    cout << nsexp::checker::disabled(nsexp::AMS1) << endl;
    cout << nsexp::checker::disabled(nsexp::AMS2) << endl;
    cout << nsexp::checker::disabled(nsexp::BESS1) << endl;
    cout << nsexp::checker::disabled(nsexp::BESS2) << endl;

    return 0;
}

答案 1 :(得分:0)

如何定义可以为枚举常量指定的保留值:

namespace nsexp{
  enum expname{
    AMS1 // = Undefined,
    AMS2 // = Undefined,
    BESS1= Undefined,
    BESS2 // = Undefined,
    ...
    };
}

if (BESS1 != Undefined) strcpy(filename[nsexp::BESS2],"bess/data_exp2");

答案 2 :(得分:0)

您可以稍微修改enum并在任何引用之前检查该值。

#include <iostream>

enum expname {
  // ENABLED
  AMS1,
  BESS1,
  BESS2,

  // DISABLED
  DISABLED,
  AMS2
};

bool enabled(expname exp) {

  return (exp < expname::DISABLED);
}

int main(const int argc, const char* argv[]) {

  std::cout << enabled(expname::AMS1) ? "enabled" : "disabled" << std::endl;
  std::cout << enabled(expname::AMS2) ? "enabled" : "disabled" << std::endl;

  return 0;
}

此输出

enabled
disabled
相关问题