【发布时间】:2020-07-25 01:27:18
【问题描述】:
假设我们有如下所示的这段代码,问题是为什么不保留 "c" 的 cv 限定符 (const) 而行为与 "v" 不同?
int main(int argc, char **argv) {
int x{};
int y{};
const auto [v] = std::tuple<int>(x);
const auto [c] = std::tuple<int&&>(std::move(y));
decltype(v) vv = 10; // vv -> const int;
decltype(c) cc = 100; // cc -> int&&;
return 0;
}
另外,我可以像下面这样用模板参数推导模拟相同类型的推导过程吗?
template<class T>
void foo(T t) { // here should be T rather than universal reference;
// mimic the same behavior as above somehow ...
}
疑问二:
对于下面的代码,“结构化绑定”的“自动”推断似乎与“自动”的正常用法不一致?
我期望的是,对于第一个“auto”,decltype(v) 应该是 const int 的类型,而不是像第二个那样的 int& 类型,因为我这样做了不要在“auto”旁边指定“&”。那么,“结构化绑定”与“auto”有什么特殊规则吗?
int main(int argc, char **argv) {
int x{};
const auto [v] = std::tuple<int&>(x); // v -> int&;
static_assert(std::is_same_v<decltype(v), int&>);
int& rx = x;
const auto c = rx; // c -> const int;
static_assert(std::is_same_v<decltype(c), const int>);
return 0;
}
【问题讨论】:
-
请注意,应用了
const限定符的int&&仍然是int&&(const对引用没有意义,因此任何添加它的尝试都无效)。限定符不会“挖掘”过去的参考/指针级别。您可以通过using T = int&&; const T t = 10;看到这一点 -
@M.M 嗨,为什么 cv-qualifier 作为参考没有任何意义?从c++设计的角度来看,相关的原则是什么?
-
重新“使用
auto进行结构化绑定”,注意结构化绑定必须始终使用auto。