从 std::tuple 成员中删除引用 [英] Remove reference from std::tuple members
问题描述
我正在 stl 元组的帮助下为某些变量实现保存/恢复功能,如下所示:
I'm implementing save/restore functionality for some variables with the help of stl tuples as follows:
double a = 1, b = 2;
int c = 3;
auto tupleRef = std::make_tuple(std::ref(a), std::ref(b), std::ref(c));
// here I'm saving current state of a, b, c
std::tuple<double, double, int> saved = tupleRef;
//here goes block of code, where a, b, and c get spoiled
......................
//
//now I'm restoring initial state of a, b, c
tupleRef = savedTuple;
此代码运行良好.但不是在
This code works well. But instead of explicit specifying tuple members types in
std::tuple<double, double, int> saved = tupleRef;
我宁愿删除所有 tupleRef 成员的引用,如下所示
I'd like to rather remove references from all tupleRef members, like in the following
auto saved = remove_ref_from_tuple_members(tupleRef);
我相信可以为此编写remove_ref_from_tuple_members"模板.
I believe that it is possible to write "remove_ref_from_tuple_members" template to that end.
感谢您的回答.
推荐答案
一个简单的类型别名可用于将 std::remove_reference
应用于元组中的所有类型.
A simple type alias can be used to apply std::remove_reference
to all types in a tuple.
template <typename... T>
using tuple_with_removed_refs = std::tuple<typename std::remove_reference<T>::type...>;
有了这个,您现在可以编写函数模板:
Armed with this you can now write the function template:
template <typename... T>
tuple_with_removed_refs remove_ref_from_tuple_members(std::tuple<T...> const& t) {
return tuple_with_removed_refs { t };
}
这篇关于从 std::tuple 成员中删除引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!