【发布时间】:2021-12-05 16:51:08
【问题描述】:
我刚刚了解了 C++ 中的结构化绑定,但有一件事我不喜欢
auto [x, y] = some_func();
是auto隐藏了x和y的类型。我必须查看some_func 的声明才能知道x 和y 的类型。或者,我可以写
T1 x;
T2 y;
std::tie(x, y) = some_func();
但这仅适用于x 和y 是默认可构造的而不是const。有没有办法写
const auto [x, y] = some_func();
对于x 和y 的非默认可构造类型,以某种方式使x 和y 的类型可见?当我将x 和y 声明为与some_func 的返回类型不兼容的东西时,编译器最好抱怨,即不是const auto /* T1, T2 */ [x, y] = some_func();。
澄清。由于我的问题下面的 cmets 似乎围绕是否使用 &,而之前的一些答案将我的问题误解为“使用哪种语法来提取返回的对的数据type”,我想我需要澄清一下我的问题。
假设我们的代码分布在多个文件中
//
// API.cpp
//
#include <utility>
class Foo {
public:
Foo () {}
};
Foo foo;
class Bar {
private:
Bar () {}
public:
static Bar create () { return Bar(); }
};
Bar bar = Bar::create();
std::pair<int, bool> get_values () {
return std::make_pair(73, true);
}
std::pair<Foo&, Bar&> get_objects () {
return std::pair<Foo&, Bar&>(foo, bar);
}
//
// Program.cpp
//
int main (int, char**) {
const auto [x, y] = get_values();
const auto& [foo, bar] = get_objects();
/* Do stuff with x, y, foo and bar */
return 0;
}
在编写此代码时,get_values 和 get_objects 的声明在我的脑海中是新鲜的,所以我知道它们的返回类型。但是一周后看Program.cpp时,我几乎不记得main中的代码,更不用说它的变量的数据类型或者get_values和get_objects的返回类型,所以我需要打开API.cpp并找到get_values 和 get_objects 了解它们的返回类型。
我的问题是是否有语法将main中变量x、y、foo和bar的数据类型写入结构化绑定?最好以允许编译器纠正我的方式,如果我犯了错误,所以没有 cmets。类似于
int main (int, char**) {
// Pseudo-Code
[const int x, const bool y] = get_values();
[const Foo& foo, const Bar& bar] = get_objects();
/* Do stuff with x, y, foo and bar */
return 0;
}
【问题讨论】:
-
编译器抱怨...只是
static_assert(std::is_same_v? -
const auto& t = some_func(); const T1 x = std::get<0>(t); const T2 y = std::get<1>(t);没有比这更明确的了。 -
"...我必须查找 some_func 的声明..." 如果您不查找声明,那么您怎么知道
auto [x, y] = some_func();在第一名? -
@RichardCritten 我认为关键在于何时回读代码。尽管如此,这并不重要......
-
使用
auto的缺点与不使用c++11 - Is there a downside to declaring variables with auto in C++? - Stack Overflow 相同(另请参阅其链接问题。)
标签: c++ c++17 structured-bindings