Namespaces
Variants

std:: ignore

From cppreference.net
Utilities library
定义于头文件 <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 ]] 函数返回值引发的警告,即使并不需要进行赋值操作。

对于需要忽略但无需赋值的值,可以将其强制转换为 void 。对于已命名但未使用其值的变量,可以将其强制转换为 void ,或使用 [[ maybe_unused ]] 属性声明这些变量。

示例

  1. 演示了将 std::ignore [[ nodiscard ]] 函数结合使用的场景。
  2. 解包由 std:: pair < iterator, bool > 返回的 std:: set :: insert ( ) 返回值,但仅保存布尔值部分。
#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 << "Value was inserted successfully.\n";
}

输出:

Value was inserted successfully.

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 2773 C++14 std::tuple 被设为 constexpr std::ignore 尚未 设为 constexpr
P2968R2 C++11 std::ignore std::tie 之外的行为未正式规范 进行完整规范

参见

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