名稱空間
變體
操作

std::ignore

來自 cppreference.com
< cpp‎ | utility‎ | tuple
 
 
 
 
定義於標頭檔案 <tuple>
在標頭檔案 <utility> 中定義
(1)
const /*ignore-type*/ ignore;
(C++11 起)
(until C++14)
constexpr /*ignore-type*/ ignore;
(C++14 起)
(inline since c++17)
(2)
struct /*ignore-type*/

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

};
(C++11 起)
(until 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::ignorenodiscard 函式的使用。
  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::ignorestd::tie 之外的行為沒有正式指定 已完全指定

[編輯] 參閱

(C++11)
建立左值引用 tuple 或將 tuple 解包為單獨的物件
(函式模板) [編輯]