c++ 解构函数 return 值
c++ destructuring function return value
抱歉,如果之前有人问过这个问题。我对此还是个新手;
所以,我有以下代码;
template<typename K, typename V>
class test_class {
std::map<K, V> my_map;
void add_kv_to_std_map ( K const& key, V const& val ) {
// And basically, i have the following syntax;
auto [it, ins] = my_map.insert_or_assign(key, val);
// Then perform other operations.
}
}
问题是,在这个语法中;
auto [it, ins] = my_map.insert_or_assign(key, val);
我真的不需要 ins
变量。是否可以只在其中检索 it
?
起初,我以为我可以做这样的事情;
auto [it, ] = my_map.insert_or_assign(key, val);
但我用那个催生了撒旦。
如有任何建议,我们将不胜感激。提前致谢。
I don't really need ins variable. Is it possible to just retrieve it in there?
没有
您可以使用传达被忽略的含义的变量名。就个人而言,我更喜欢下划线(注意下划线是全局命名空间中的保留标识符,所以不要在那里使用)。
您可以使用 [[maybe_unused]]
属性向编译器表示有意未使用该绑定:
[[maybe_unused]] auto [it, _] = ...
如果您使用 std::tie
而不是结构化绑定,那么在这种情况下您可以使用 std::ignore
:
std::map<K, V>::iterator it;
std::tie(it, std::ignore) = ...
抱歉,如果之前有人问过这个问题。我对此还是个新手;
所以,我有以下代码;
template<typename K, typename V>
class test_class {
std::map<K, V> my_map;
void add_kv_to_std_map ( K const& key, V const& val ) {
// And basically, i have the following syntax;
auto [it, ins] = my_map.insert_or_assign(key, val);
// Then perform other operations.
}
}
问题是,在这个语法中;
auto [it, ins] = my_map.insert_or_assign(key, val);
我真的不需要 ins
变量。是否可以只在其中检索 it
?
起初,我以为我可以做这样的事情;
auto [it, ] = my_map.insert_or_assign(key, val);
但我用那个催生了撒旦。
如有任何建议,我们将不胜感激。提前致谢。
I don't really need ins variable. Is it possible to just retrieve it in there?
没有
您可以使用传达被忽略的含义的变量名。就个人而言,我更喜欢下划线(注意下划线是全局命名空间中的保留标识符,所以不要在那里使用)。
您可以使用 [[maybe_unused]]
属性向编译器表示有意未使用该绑定:
[[maybe_unused]] auto [it, _] = ...
如果您使用 std::tie
而不是结构化绑定,那么在这种情况下您可以使用 std::ignore
:
std::map<K, V>::iterator it;
std::tie(it, std::ignore) = ...