std :: errc,如何在retval中表示成功

use*_*942 7 c++ c++14

我想写一个像这样的c ++函数:

#include <system_error>
std::errc f() { return std::errc::success; }
Run Code Online (Sandbox Code Playgroud)

但我无法理解如何使用std :: errc'enum class'type返回成功的值(在本例中为0).我看到的一种方法是返回int:

template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) {
    return static_cast<typename std::underlying_type<E>::type>(e);
}

int f() { is_succ() ? 0 : to_underlying(err); }
Run Code Online (Sandbox Code Playgroud)

但它对我来说看起来很难看.是从标准c ++ 0x14中的函数返回面向C的成功/错误代码的标准方法吗?

PS.我正在使用MS VC 2015补丁2.

Pet*_*man 5

您通常不会std::errc直接从函数返回值。相反,您返回一个std::error_code. 例如,您的函数将像这样声明:

std::error_code f();
Run Code Online (Sandbox Code Playgroud)

然后将该函数的结果与 std::errc 值进行比较。例如:

std::error_code error = f();
if (error == std::errc::no_such_file_or_directory)
{
  // deal with the error
}
Run Code Online (Sandbox Code Playgroud)

std::error_code是上下文可转换的 bool。测试函数是否成功的方法是在布尔表达式中使用错误代码。例如:

std::error_code error = f();
if (error)
{
  // the function failed...
}
Run Code Online (Sandbox Code Playgroud)

要从这样的函数返回成功,您需要返回一个默认的已初始化的std::error_code. 例如:

std::error_code f()
{
  // do stuff...
  return std::error_code{}; // success!
}
Run Code Online (Sandbox Code Playgroud)

当您使用C 风格的 API时,这种方法很有效。您的包装器将std::error_code使用 API 返回的整数值和std::error_category定义如何将这些错误转换为std::errc值的自定义来构造对象。

然而,相反的做法是行不通的。如果您正在为 C++ 库编写 C 包装器,那么您必须以 C 方式做事。enum使用您的错误值定义 an并从您的 C 入口点返回这些值。


Dan*_*iel 5

你可以这样做:

#include <system_error>

std::errc f() { return std::errc(); }

int main()
{
    std::errc x = f();
    if (x == std::errc())
    {
        // success
    }
}
Run Code Online (Sandbox Code Playgroud)

std::errc() (0) 是一个有效的枚举值,即使它没有出现在从 1 开始的枚举器列表中。它代表成功。

为了进行比较,请查看std::to_chars,它返回一个

struct to_chars_result {
    char* ptr;
    std::errc ec;
}
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica -1

文档中:

作用域枚举std::errc定义了与 POSIX 错误代码相对应的可移植错误条件的值。

std::errc常量用于在检查是否发生某些特定错误情况时进行比较(如该页面上的示例所示)。

成功不是错误条件。

返回一个std::error_code相反,它可能包装这些错误条件之一,或者默认情况下没有错误条件(即成功)。

  • `std::from_chars` 在成功时返回一个值初始化的 `errc`,因此它不仅仅用于错误。 (2认同)