gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:19:21 27 4
gpt4 key购买 nike

我在命名空间中定义了一长串枚举成员:

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");

最佳答案

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

#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;
}

预期输出:

0
1
0
1

关于c++ - 检查是否已定义枚举成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33554861/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com