“ 20.3.6 多态变体”小节描述了如何在 C 中识别多态变体值(*它包含一个错误:应该是caml_hash_variant
而不是hash_variant
)
我想直接将这些哈希值用作 C++ 中的错误代码。类似的东西
存档.mli:
...
type t = ...
type err = [`File_not_found | `Archive_is_corrupted]
val opena : string -> (t, err) error
...
存档.ml
...
let () = Callback.register "open archive" opena
...
存档.cpp:
...
const int Error::File_not_found = caml_hash_variant("File_not_found")
const int Error::Archive_is_corrupted = caml_hash_variant("Archive_is_corrupted")
int Archive::open(char* path) {
static const value* f = nullptr; \
if (f = nullptr)
f = caml_named_value("open archive");
value result = caml_callback(*f, caml_copy_string(path));
if (Tag_val(result) == 0) { // Result.Ok
archive = Field(caml_state, 0);
return ??????
} else { // Result.Error
return Int_val(Field(caml_state, 0));
}
}
...
返回错误代码并进行比较没有问题
if (x.open(path) == Error::Archive_is_corrupted) {
...
}
但我不知道我可以返回什么状态。0? -1?
是否存在无法返回的保证值caml_hash_variant
?