访问和打印元组中的数据,并使用 C++14 的模板函数显示它
access and print data in a tuple and display it using a template function using C++14
我有如下列表
my_mixed_list = {"Sample String", int_value, user_data_type}
我想使用 C++11 std::tuple 以简单的白色分隔方式显示上面的列表。
可能是这样的:
template <typename T>
void display_mixed_items (std::tuple <T> mixed) {
for (const auto& mixed_ele : mixed) std::cout << mixed_ele << " ";
}
我知道我必须重载 ostream 运算符才能显示用户定义的数据。但我希望你能回答这个问题。
我不确定为什么编译器会抱怨参数列表。什么是完成上述任务的正确方法。无法在 Whosebug 上找到确切答案,所以提一下。
在Python中我们可以简单地使用list和tada!但是,如果不是元组,还有其他方法可以使用可变参数模板或其他方法。
使用 Sean Parent 现在著名的 "for each argument":
template <class F, class... Args>
void for_each_argument(F f, Args&&... args) {
[](...){}((f(std::forward<Args>(args)), 0)...);
}
其中 f
是将您的论点流式传输到 std::cout
的东西。
另请参阅:
How can you iterate over the elements of an std::tuple?
您可以通过创建自己的 for_tuple
函数来遍历元组:
template<typename T, typename F, std::size_t... S>
void for_tuple_impl(std::index_sequence<S...>, T&& tup, F& function) {
using expand_t = int[];
(void) expand_t{(void(function(std::get<S>(std::forward<T>(tup)))), 0)..., 0};
}
template<typename T, typename F>
void for_tuple(T&& tup, F function) {
for_tuple_impl(
std::make_index_sequence<std::tuple_size<std::decay_t<T>>::value>{},
std::forward<T>(tup),
function
);
}
然后像这样使用它:
for_tuple(my_tuple, [](auto&& mixed_ele){ std::cout << mixed_ele << ' '; });
C++23 想要创建一个称为 template for
的语言特性来替换那堆括号和括号(尚未正式):
template for (auto&& mixed_ele : mixed) {
std::cout << mixed_ele << ' ';
}
我有如下列表
my_mixed_list = {"Sample String", int_value, user_data_type}
我想使用 C++11 std::tuple 以简单的白色分隔方式显示上面的列表。 可能是这样的:
template <typename T>
void display_mixed_items (std::tuple <T> mixed) {
for (const auto& mixed_ele : mixed) std::cout << mixed_ele << " ";
}
我知道我必须重载 ostream 运算符才能显示用户定义的数据。但我希望你能回答这个问题。 我不确定为什么编译器会抱怨参数列表。什么是完成上述任务的正确方法。无法在 Whosebug 上找到确切答案,所以提一下。
在Python中我们可以简单地使用list和tada!但是,如果不是元组,还有其他方法可以使用可变参数模板或其他方法。
使用 Sean Parent 现在著名的 "for each argument":
template <class F, class... Args>
void for_each_argument(F f, Args&&... args) {
[](...){}((f(std::forward<Args>(args)), 0)...);
}
其中 f
是将您的论点流式传输到 std::cout
的东西。
另请参阅:
How can you iterate over the elements of an std::tuple?
您可以通过创建自己的 for_tuple
函数来遍历元组:
template<typename T, typename F, std::size_t... S>
void for_tuple_impl(std::index_sequence<S...>, T&& tup, F& function) {
using expand_t = int[];
(void) expand_t{(void(function(std::get<S>(std::forward<T>(tup)))), 0)..., 0};
}
template<typename T, typename F>
void for_tuple(T&& tup, F function) {
for_tuple_impl(
std::make_index_sequence<std::tuple_size<std::decay_t<T>>::value>{},
std::forward<T>(tup),
function
);
}
然后像这样使用它:
for_tuple(my_tuple, [](auto&& mixed_ele){ std::cout << mixed_ele << ' '; });
C++23 想要创建一个称为 template for
的语言特性来替换那堆括号和括号(尚未正式):
template for (auto&& mixed_ele : mixed) {
std::cout << mixed_ele << ' ';
}