具有结构化绑定的不同cv限定符

时间:2017-04-21 08:03:30

标签: c++ c++17

C ++ 17中的structured binding declaration允许多个不同的选项,例如:

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

2 个答案:

答案 0 :(得分:8)

不 - proposal的Q&amp; A:

涵盖了这一点
  
    

是否应该扩展语法以允许const /&amp; -qualifying个人姓名的类型?

  
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);

答案 1 :(得分:5)

这是不允许的,但似乎对结构化绑定的工作方式存在一些误解。以下是您的代码段的实际工作方式:

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&`.

根据您提供的示例,似乎错误在于认为auto 中的auto [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);
相关问题