std::ignore
来自cppreference.com
在标头 <tuple> 定义
|
||
在标头 <utility> 定义
|
||
(1) | ||
const /*ignore-type*/ ignore; |
(C++11 起) (C++14 前) |
|
constexpr /*ignore-type*/ ignore; |
(C++14 起) (c++17 起 inline) |
|
(2) | ||
struct /*ignore-type*/ { |
(C++11 起) (C++14 前) (仅用于阐述*) |
|
struct /*ignore-type*/ { |
(C++14 起) (仅用于阐述*) |
|
1) 能把任何值赋给它,且赋值无效果的对象。
2)
std::ignore
的类型。注解
不能将 void 表达式或 volatile 位域值赋值给 std::ignore
。
std::ignore
最初的意图是在 std::tie 解包 std::tuple 时作为不使用实参的占位符。
一些编码指南建议使用 std::ignore
来避免 [[nodiscard]]
函数的未使用返回值造成的警告。
示例
- 演示
std::ignore
和[[nodiscard]]
函数一起使用。 - 解包 std::set::insert() 所返回的 std::pair<iterator, bool>,但仅保存布尔值。
运行此代码
#include <iostream> #include <set> #include <string> #include <tuple> [[nodiscard]] int dontIgnoreMe() { return 42; } int main() { std::ignore = dontIgnoreMe(); std::set<std::string> set_of_str; if (bool inserted{false}; std::tie(std::ignore, inserted) = set_of_str.insert("Test"), inserted) std::cout << "已成功插入值。\n"; }
输出:
已成功插入值。
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2773 | C++14 | 已经使 std::tuple 为 constexpr 但未对 std::ignore 如此
|
亦使之为 constexpr |
P2968R2 | C++11 | 未正式规定 std::ignore 在 std::tie 以外的行为
|
完全规定行为 |
参阅
(C++11) |
创建左值引用的 tuple,或将元组解包为独立对象 (函数模板) |