Skip to content

Commit

Permalink
error_codeのコンストラクタ : ErrorCodeEnumをとるオーバーロードの使用例を記載
Browse files Browse the repository at this point in the history
  • Loading branch information
faithandbrave committed May 24, 2024
1 parent 2424d15 commit 0eeefc0
Showing 1 changed file with 61 additions and 3 deletions.
64 changes: 61 additions & 3 deletions reference/system_error/error_code/op_constructor.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ error_code(ErrorCodeEnum e) noexcept; // (3)
## 備考
- (3) : [`is_error_code_enum`](../is_error_code_enum.md)が`false`となる場合、この関数はオーバーロード解決から除外される。
- (3) : [`is_error_code_enum`](../is_error_code_enum.md)が`false`となる場合、この関数はオーバーロード解決から除外される
- (3) : [`make_error_code()`](../make_error_code.md)の呼び出しに`std::`名前空間がついていないことにより、指定された`ErrorCodeEnum`型が定義されている名前空間の`make_error_code()`関数がADLによって探索される
## 例
### 基本的な使い方
```cpp example
#include <iostream>
#include <system_error>
Expand Down Expand Up @@ -107,7 +109,7 @@ int main()
* std::errc::invalid_argument[link /reference/system_error/errc.md]
* std::generic_category()[link /reference/system_error/generic_category.md]

### 出力
#### 出力
```
default ctor
success
Expand All @@ -125,6 +127,63 @@ error
generic
```

### 独自のエラーコードを定義する例
```cpp example
#include <iostream>
#include <system_error>
#include <type_traits>

namespace mylib {

enum class my_error {
not_found,
};

class my_error_category : public std::error_category {
public:
const char* name() const noexcept override
{
return "my_error_category";
}

std::string message(int value) const override
{
if (value == static_cast<int>(my_error::not_found))
return "not found";
return "unknown";
}
};

const my_error_category& get_my_error_category() {
static my_error_category cat;
return cat;
}

std::error_code make_error_code(my_error err)
{
return std::error_code(static_cast<int>(err), get_my_error_category());
}
}

namespace std {
template <>
struct is_error_code_enum<mylib::my_error> : public std::true_type {};
}

int main() {
// ecにはmy_error_categoryが設定される
std::error_code ec = mylib::my_error::not_found;
std::cout << ec.message() << std::endl;
}
```
* ec.message()[link message.md]
* std::error_category[link /reference/system_error/error_category.md]
#### 出力
```
not found
```
## バージョン
### 言語
- C++11
Expand All @@ -136,4 +195,3 @@ generic
- [Visual C++](/implementation.md#visual_cpp): 2010 (enum class未対応のため、ErrorCodeEnumのコンストラクタは動作しない)
## 参照

0 comments on commit 0eeefc0

Please sign in to comment.