簡體   English   中英

具有結構化綁定的不同 cv 限定符

[英]Different cv-qualifiers with structured bindings

C++17 中的結構化綁定聲明允許幾個不同的選項,例如:

std::tuple<int, int> foo();

auto  [a, b] = foo(); // a and b are: int
const auto  [a, b] = foo(); // a and b are: int const
const auto& [a, b] = foo(); // a and b are: int const&

有沒有辦法給ab不同的 cv 限定符? 例如a的類型為intb的類型為int const

不 - 這在提案的問答中有所涉及:

是否應該擴展語法以允許const /& - 限定個人姓名的類型?

 auto [& x, const y, const& z] = f(); // NOT proposed 

我們認為答案應該是否定的。 這是一個簡單的功能,用於存儲值並將名稱綁定到其組件,而不是聲明多個變量。 允許這樣的限定將是特征蠕變,將特征擴展為不同的東西,即聲明多個變量的方式。 如果我們確實要聲明多個變量,我們已經有了拼寫它的方法:

 auto val = f(); // or auto&& T1& x = get<0>(val); T2 const y = get<1>(val); T3 const& z = get<2>(val); 

這是不允許的,但似乎對結構化綁定的工作方式存在一些誤解。 以下是您的代碼段的實際工作方式:

std::tuple<int, int> foo();

auto  [a, b] = foo(); // `a` and `b` are `int`
auto& [a, b] = foo(); // error: cannot bind a non-const lvalue-ref to an rvalue.
const auto  [a, b] = foo(); // `a` and `b` are: `int const`
const auto& [a, b] = foo(); // `a` and `b` are: `int const`! (NOT `int const&`)
                            // lifetime extension of `foo()` via `const&`.

根據您所提供的示例中,這似乎是這個錯誤是以為autoauto [a, b]跨變量分布 它不是。 auto實際上是初始化程序的類型。 在C ++中,這大致編碼如下:

auto temp = foo();  // `auto` is for the initializer!
// These aren't actually references, but close.
auto&& a = std::get<0>(temp);
auto&& b = std::get<1>(temp);

這與以下內容相反:

auto&& temp = foo();  // save `temp` like range-based `for` does!
// if `auto` in `auto [a, b]` were distributive.
auto a = std::get<0>(temp);
auto b = std::get<1>(temp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM