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]]
函数的未使用返回值造成的警告,即便并不需要赋值操作。
转换到 void 是一种忽视值但不使用赋值的方式。对于不使用它的值且有名字的变量,可以使用转换到 void 或者在声明它们的时候使用 [[maybe_unused]]
。
示例
运行此代码
#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,或将元组解包为独立对象 (函数模板) |