std::ignore

来自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
在标头 <tuple> 定义
在标头 <utility> 定义
(1)
const /*ignore-type*/ ignore;
(C++11 起)
(C++14 前)
constexpr /*ignore-type*/ ignore;
(C++14 起)
(c++17 起 inline)
(2)
struct /*ignore-type*/

{
    template< class T >
    const /*ignore-type*/& operator=( const T& ) const noexcept
    {
        return *this;
    }

};
(C++11 起)
(C++14 前)
(仅用于阐述*)
struct /*ignore-type*/

{
    template< class T >
    constexpr const /*ignore-type*/& operator=( const T& ) const noexcept
    {
        return *this;
    }

};
(C++14 起)
(仅用于阐述*)
1) 能把任何值赋给它,且赋值无效果的对象。
2) std::ignore 的类型。

注解

不能将 void 表达式或 volatile 位域值赋值给 std::ignore

std::ignore 最初的意图是在 std::tie 解包 std::tuple 时作为不使用实参的占位符。

一些编码指南建议使用 std::ignore 来避免 [[nodiscard]] 函数的未使用返回值造成的警告。

示例

  1. 演示 std::ignore[[nodiscard]] 函数一起使用。
  2. 解包 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::tupleconstexpr 但未对 std::ignore 如此 亦使之为 constexpr
P2968R2 C++11 未正式规定 std::ignorestd::tie 以外的行为 完全规定行为

参阅

(C++11)
创建左值引用的 tuple,或将元组解包为独立对象
(函数模板)