我的目标
我有多个函数将返回大量错误代码列表。 某些函数将使用“错误代码列表”中相同且不同的错误代码
- 例如:
fun1()
将仅返回errorcode1
或errorcode2
(errorcode2 仅在此函数中使用)fun2()
将仅返回errorcode1
或errorcode3
(但这两个函数中都使用了 errorcode1)
所需的解决方案应考虑以下几点: -
定义哪个函数可以返回什么错误代码
如果任何函数尝试返回不适合该函数的错误代码,则会出现编译错误
- 无论函数返回或抛出什么,都必须可转换为 int(因为这些函数将成为 C API 的一部分)
我的方法
到目前为止,我考虑过使用枚举的选项,但解决方案对我没有吸引力
- 为每个函数定义一个单独的枚举
- 为所有函数定义一个全局枚举
为每个函数定义一个单独的枚举
enum errorcodefun1 {errorcode1=1, errorcode2=2}; // OK at least it is expressed what is expected for fun1
errorcodefun1 fun1() { };
enum errorcodefun2 {errorcode1_fun2=1, errorcode3_fun2=3 }; // minor problem: not expressing that errorcode1_fun2 is logical same as errorcode1
函数越多(部分使用相同的错误代码),我得到的代码重复就越多。
为所有函数定义一个枚举
enum errorcodes {errorcode1=1, errorcode2=2, errorcode3=3};
errorcode fun1() {... } //do not like because I will get no compilation error if it returns errorcode3. Only errorcode1 and errocode2 is intended
errorcode fun2() {... }
我的问题
我正在考虑编写一个模拟枚举的类,但到目前为止我看到了满足我所有需求的解决方案。
您对如何实现我的目标有一些建议或想法吗?
最佳答案
采用方法 #1 但要保持安全并表达枚举成员的等效性怎么样?
enum generic_error {
ERR_OK,
ERR_NOMEM,
ERR_IO,
ERR_GENERIC
};
enum first_error {
FIRSTERR_OK = ERR_OK,
FIRSTERR_NOMEM = ERR_NOMEM
};
enum second_error {
SECONDERR_OK = ERR_OK,
SECONDERR_IO = ERR_IO
};
int main()
{
enum first_error f = FIRSTERR_OK;
enum second_error s = SECONDERR_OK;
assert(f == s); // never fires
return 0;
}
但这并不是特别好的做法...如果我是你,我真的会选择使用一个常见的错误代码枚举。
关于c++ - 只允许枚举的子集作为返回值 - 或如何让编译器提醒我?在 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19727160/